exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | f4a10a561661e2e65025ec0ddabeaaa8 | train_002.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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
static HashMap<Long, Long> hm;
public void solve(int testNumber, InputReader fi, PrintWriter out) {
int i, j, q;
q = fi.nextInt();
hm = new HashMap<>();
while (q-- > 0) {
int type = fi.nextInt();
if (type == 1) {
long a = fi.nextLong();
long b = fi.nextLong();
long w = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
addEdge(a, w);
a = a / 2;
}
while (b != lca) {
addEdge(b, w);
b = b / 2;
}
} else if (type == 2) {
long ans = 0;
long a = fi.nextLong();
long b = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
ans += hm.containsKey(a) ? hm.get(a) : 0;
a = a / 2;
}
while (b != lca) {
ans += hm.containsKey(b) ? hm.get(b) : 0;
b = b / 2;
}
out.println(ans);
}
}
}
static long getLCA(long a, long b) {
ArrayList<Long> path1 = new ArrayList<Long>();
ArrayList<Long> path2 = new ArrayList<Long>();
while (a > 0) {
path1.add(a);
a = a / 2;
}
while (b > 0) {
path2.add(b);
b = b / 2;
}
Collections.reverse(path1);
Collections.reverse(path2);
long lca = -1;
for (int i = 0; i < path1.size() && i < path2.size(); i++) {
if (path1.get(i).equals(path2.get(i))) lca = path1.get(i);
}
return lca;
}
void addEdge(long u, long w) {
if (hm.containsKey(u)) {
hm.put(u, hm.get(u) + w);
} else hm.put(u, w);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 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 | ["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 | 3d6cabb5bdb356f1ec2a4ff8128e41f5 | train_002.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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
static HashMap<Long, Long> hm;
public void solve(int testNumber, InputReader fi, PrintWriter out) {
int i, j, q;
q = fi.nextInt();
hm = new HashMap<>();
while (q-- > 0) {
int type = fi.nextInt();
if (type == 1) {
long a = fi.nextLong();
long b = fi.nextLong();
long w = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
addEdge(a, w);
a = a / 2;
}
while (b != lca) {
addEdge(b, w);
b = b / 2;
}
} else if (type == 2) {
long ans = 0;
long a = fi.nextLong();
long b = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
ans += hm.containsKey(a) ? hm.get(a) : 0;
a = a / 2;
}
while (b != lca) {
ans += hm.containsKey(b) ? hm.get(b) : 0;
b = b / 2;
}
out.println(ans);
}
}
}
static long getLCA(long a, long b) {
ArrayList<Long> path1 = new ArrayList<>();
ArrayList<Long> path2 = new ArrayList<>();
while (a > 0) {
path1.add(a);
a = a / 2;
}
while (b > 0) {
path2.add(b);
b = b / 2;
}
Collections.reverse(path1);
Collections.reverse(path2);
/*System.out.println(" path1 " +path1);
System.out.println(" path2 " +path2);*/
long lca = -1;
for (int i = 0; i < path1.size() && i < path2.size(); i++) {
if (path1.get(i).equals(path2.get(i))) lca = path1.get(i);
}
//System.out.println(" lca " +lca);
return lca;
}
void addEdge(long u, long w) {
if (hm.containsKey(u)) {
hm.put(u, hm.get(u) + w);
} else hm.put(u, w);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 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 | ["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 | 6162f1a2785d0264f4dd03c5b7d6cbd9 | train_002.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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
static HashMap<Long, Long> hm;
public void solve(int testNumber, InputReader fi, PrintWriter out) {
int i, j, q;
q = fi.nextInt();
hm = new HashMap<>();
while (q-- > 0) {
int type = fi.nextInt();
if (type == 1) {
long a = fi.nextLong();
long b = fi.nextLong();
long w = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
addEdge(a, w);
a = a / 2;
}
while (b != lca) {
addEdge(b, w);
b = b / 2;
}
} else if (type == 2) {
long ans = 0;
long a = fi.nextLong();
long b = fi.nextLong();
long lca = getLCA(a, b);
while (a != lca) {
ans += hm.containsKey(a) ? hm.get(a) : 0;
a = a / 2;
}
while (b != lca) {
ans += hm.containsKey(b) ? hm.get(b) : 0;
b = b / 2;
}
out.println(ans);
}
}
}
long getLCA(long v, long u) {
List<Long> a = new ArrayList<Long>();
List<Long> b = new ArrayList<Long>();
while (v > 0) {
a.add(v);
v /= 2;
}
while (u > 0) {
b.add(u);
u /= 2;
}
Collections.reverse(a);
Collections.reverse(b);
long res = -1;
for (int i = 0; i < a.size() && i < b.size(); ++i) {
if (a.get(i).equals(b.get(i))) {
res = a.get(i);
}
}
return res;
}
void addEdge(long u, long w) {
if (hm.containsKey(u)) {
hm.put(u, hm.get(u) + w);
} else hm.put(u, w);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 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 | ["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 | 539d1609169c56c61c00f7955258f2bd | train_002.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.*;
import java.io.*;
import java.lang.*;
public class Forces{
public static PrintWriter cout;
public static boolean[] visited;
public static int ans=0;
public static void main(String ...arg) throws IOException
{
Read cin = new Read();
//InputReader cin = new InputReader(System.in);
//Scan cin =new Scan();
cout = new PrintWriter(new BufferedOutputStream(System.out));
HashMap<Long,Long> map = new HashMap<>();
int q = cin.nextInt();
for(int i=0;i<q;i++)
{
int op = cin.nextInt();
long u = cin.nextLong();
long v = cin.nextLong();
if(op == 1)
{
long w = cin.nextLong();
while(u!=v)
{
if(u>v)
{
if(map.containsKey(u))
map.put(u,map.get(u)+w);
else
map.put(u,w);
u/=2;
}
else
{
if(map.containsKey(v))
map.put(v,map.get(v)+w);
else
map.put(v,w);
v/=2;
}
}
}
else
{
long cost =0;
while(u!=v)
{
if(u>v)
{
if(map.containsKey(u))
cost+=map.get(u);
u/=2;
}
else
{
if(map.containsKey(v))
cost+=map.get(v);
v/=2;
}
}
cout.println(cost);
}
}
cout.close();
}
static class InputReader {
final InputStream is;
final byte[] buf = new byte[1024];
int pos;
int size;
public InputReader(InputStream is) {
this.is = is;
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = read();
} while (!isWhitespace(c));
return res * sign;
}
int read() {
if (size == -1)
throw new InputMismatchException();
if (pos >= size) {
pos = 0;
try {
size = is.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (size <= 0)
return -1;
}
return buf[pos++] & 255;
}
static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
}
class Read
{
private BufferedReader br;
private StringTokenizer st;
public Read()
{ 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 | ["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 | 79e9723166e3e4356ed1f9566913c961 | train_002.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.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
public class A implements Runnable{
final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
void solve() {
Map<Long, Long> costs = new HashMap<Long, Long>();
Set<Long> way = new LinkedHashSet<Long>();
int queries = readInt();
while (queries --> 0) {
int type = readInt();
long u = readLong();
long v = readLong();
way.clear();
for (long cur = u; cur > 0; cur >>= 1) {
way.add(cur);
}
long lca = 0;
for (long cur = v; cur > 0; cur >>= 1) {
if (way.contains(cur)) {
lca = cur;
break;
} else {
way.add(cur);
}
}
if (type == 1) {
long cost = readLong();
for (long node : way) {
if (node > lca) {
Long curCost = costs.get(node);
if (curCost == null) curCost = 0L;
costs.put(node, curCost + cost);
}
}
} else {
long cost = 0;
for (long node : way) {
if (node > lca) {
Long curCost = costs.get(node);
if (curCost == null) curCost = 0L;
cost += curCost;
}
}
out.println(cost);
}
}
}
boolean isPrime(int x) {
for (int d = 2; d * d <= x; ++d) {
if (x % d == 0) return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////
final boolean FIRST_INPUT_STRING = false;
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
while (true) {
try {
solve();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
}
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new A(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
char[] readCharArray() {
return readLine().toCharArray();
}
char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
int readInt() {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() {
return Long.parseLong(readString());
}
long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() {
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
public RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
static final boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
}
| Java | ["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 | 61669d527972c13f963d116a41ed0750 | train_002.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.*;
import java.util.*;
public class A {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void solve() throws IOException {
int t = 1;
while (t-- > 0) {
solveTest();
}
}
class Edge implements Comparable<Edge> {
long x;
long y;
public Edge(long x, long y) {
if(x > y) {
long tmp = x;
x = y;
y = tmp;
}
this.x = x;
this.y = y;
}
@Override
public int compareTo(Edge o) {
int res = Long.compare(this.x, o.x);
if(res != 0) return res;
return Long.compare(this.y, o.y);
}
}
void solveTest() throws IOException {
int q = readInt();
Map<Edge, Long> added = new TreeMap<>();
for(int i = 0; i < q; i++) {
int t = readInt();
long v = readLong();
long u = readLong();
List<Long> path = path(v, u);
if(t == 1) {
long w = readLong();
for(int j = 0; j < path.size() - 1; j++) {
Edge e = new Edge(path.get(j), path.get(j+1));
added.compute(e, (key, old) -> old == null ? w : old + w);
}
} else {
long res = 0;
for(int j = 0; j < path.size() - 1; j++) {
Edge e = new Edge(path.get(j), path.get(j+1));
res += added.getOrDefault(e, 0l);
}
out.println(res);
}
}
}
List<Long> path(long x, long y) {
if(x > y) {
long tmp = x;
x = y;
y = tmp;
}
int xLvl = lvl(x);
int yLvl = lvl(y);
List<Long> resX = new ArrayList<>();
List<Long> resY = new ArrayList<>();
while (yLvl != xLvl) {
yLvl--;
resY.add(y);
y /= 2;
}
while (x != y) {
resX.add(x);
resY.add(y);
x /= 2;
y /= 2;
}
Collections.reverse(resY);
resX.add(x);
resX.addAll(resY);
return resX;
}
int lvl(long x) {
int res = 0;
while(x != 1) {
res++;
x /= 2;
}
return res;
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | 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 | 7192905adcfe0e3d51b00ae04f960eb9 | train_002.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.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
HashMap<String,Long> data = new HashMap<String,Long>();
for(int i=0;i<n;i++){
int t = scanner.nextInt();
long a = Long.valueOf(scanner.next());
long b = Long.valueOf(scanner.next());
if(t==1){
long w = scanner.nextInt();
while(b!=a){
if(b>a){
if(data.get(String.valueOf(b))==null){
data.put(String.valueOf(b), 0l);
}
data.put(String.valueOf(b), data.get(String.valueOf(b))+w);
if(b%2==0){
b/=2;
}else{
b = (b-1)/2;
}
}else{
if(data.get(String.valueOf(a))==null){
data.put(String.valueOf(a), 0l);
}
data.put(String.valueOf(a), data.get(String.valueOf(a))+w);
if(a%2==0){
a/=2;
}else{
a = (a-1)/2;
}
}
}
}else{
long sum = 0;
while(b!=a){
if(b>a){
if(data.get(String.valueOf(b))!=null){
sum+=data.get(String.valueOf(b));
}
if(b%2==0){
b/=2;
}else{
b = (b-1)/2;
}
}else{
if(data.get(String.valueOf(a))!=null){
sum+=data.get(String.valueOf(a));
}
if(a%2==0){
a/=2;
}else{
a = (a-1)/2;
}
}
}
System.out.println(sum);
}
}
}
} | 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 | cd97f64883b1505e34f8cdc3d6b89da1 | train_002.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.*;
import java.util.*;
public class c{
static int mod=1000000007;
static PrintWriter out = new PrintWriter(System.out);
static class pair{
long x,y;
pair(long a,long b){
x=a;
y=b;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pair other = (pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int hashCode() {
return((int)(x-y));
}
}
static void add(HashMap<pair,Long> hm,long u,long v,long w){
while(u!=v){
if(u<v){
long t = v/2;
pair p = new pair(t,v);
if(hm.containsKey(p))
hm.put(p,hm.get(p)+w);
else
hm.put(p,w);
v=t;
}
else{
long t = u/2;
pair p = new pair(t,u);
if(hm.containsKey(p))
hm.put(p,hm.get(p)+w);
else
hm.put(p,w);
u=t;
}
}
}
static long give_answer(HashMap<pair,Long> hm,long u,long v){
long ans=0;
while(u!=v){
if(u<v){
long t =v/2;
pair p = new pair(t,v);
if(hm.containsKey(p))
ans = ans+hm.get(p);
v=t;
}
else {
long t =u/2;
pair p = new pair(t,u);
if(hm.containsKey(p))
ans = ans+hm.get(p);
u=t;
}
}
return ans;
}
public static void main(String[] args){
int q = ni();
HashMap<pair,Long> hm = new HashMap();
for(int uu=1;uu<=q;uu++){
int t = ni();
if(t==1){
long u = nl();
long v = nl();
long w = nl();
add(hm,Math.max(u,v),Math.min(u,v),w);
}
else{
long u = nl();
long v = nl();
out.println(give_answer(hm,Math.max(u,v),Math.min(u,v)));
}
}
out.flush();
}
static FastReader sc=new FastReader();
static int ni(){
int x = sc.nextInt();
return(x);
}
static long nl(){
long x = sc.nextLong();
return(x);
}
static String n(){
String str = sc.next();
return(str);
}
static String ns(){
String str = sc.nextLine();
return(str);
}
static double nd(){
double d = sc.nextDouble();
return(d);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["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 | 9c60ed0a34cbfa8fc9092c64aa3dc669 | train_002.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 | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
Map<Long, Long> hm = new HashMap<>();
void solve() throws IOException {
int q = nextInt();
for (int i = 0; i < q; i++) {
int t = nextInt();
if (t == 1) {
long u = nextLong();
long v = nextLong();
long w = nextLong();
while (u != v) {
if (u > v) {
hm.put(u, hm.getOrDefault(u, 0L) + w);
u = u / 2;
}
else {
hm.put(v, hm.getOrDefault(v, 0L) + w);
v = v / 2;
}
}
}
else {
long u = nextLong();
long v = nextLong();
long sum = 0;
while (u != v) {
if (u > v) {
sum += hm.getOrDefault(u, 0L);
u = u / 2;
}
else {
sum += hm.getOrDefault(v, 0L);
v = v / 2;
}
}
outln(sum);
}
}
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| 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 | 841b2742dda0b17f823e56d4ea90266d | train_002.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.TreeMap;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.util.Map;
import java.util.Collection;
import java.io.OutputStream;
import java.util.Collections;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
Map<Long, Long> parEdgeCost = new TreeMap<>();
ArrayList<Long> generatePath(long v) {
ArrayList<Long> res = new ArrayList<>();
while (v != 1) {
res.add(v);
v /= 2;
}
Collections.reverse(res);
return res;
}
ArrayList<Long> combine(long v, long u) {
ArrayList<Long> pv = generatePath(v);
ArrayList<Long> pu = generatePath(u);
int p = 0;
while (p < pv.size() && p < pu.size() && pv.get(p).equals(pu.get(p)))
p++;
ArrayList<Long> res = new ArrayList<>(pv.subList(p, pv.size()));
res.addAll(pu.subList(p, pu.size()));
return res;
}
long getCost(ArrayList<Long> vs) {
long res = 0;
for (long v : vs)
res += parEdgeCost.getOrDefault(v, 0L);
return res;
}
void addCost(ArrayList<Long> vs, long delta) {
for (long v : vs)
parEdgeCost.put(v, parEdgeCost.getOrDefault(v, 0L) + delta);
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
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();
addCost(combine(v, u), w);
} else {
long v = in.nextLong();
long u = in.nextLong();
out.println(getCost(combine(v, u)));
}
}
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
| 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 | 0c36845830ad4a224b8bbc167916c9c0 | train_002.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.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class LorenzoVonMatterhorn {
static long ans;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int q = sc.nextInt();
edgelist = new TreeMap<>();
while(q-->0) {
int t = sc.nextInt();
long u = sc.nextLong(), v = sc.nextLong();
if (t == 1) {
long w = sc.nextLong();
update(u, v, w);
}
else {
ans = 0;
path(u, v);
out.println(ans);
}
}
out.flush();
out.close();
}
static TreeSet<Long> visited;
static TreeMap<Edge, Long> edgelist;
static boolean stop;
static void update(long u, long v, long w) {
visited = new TreeSet<>();
stop = false;
update_value1(Math.max(u, v), Math.min(u, v), w);
if (stop)
return;
long c = update_value2(Math.min(u, v), w);
update_finish(c, w);
}
static void update_value1(long u, long dist, long weight) {
visited.add(u);
if (u == dist) {
stop = true;
return;
}
if (u == 1)
return;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
if (edgelist.containsKey(e)) {
long w = edgelist.get(e);
edgelist.put(e, w + weight);
}
else
edgelist.put(e, weight);
update_value1(p, dist, weight);
}
static long update_value2(long u, long weight) {
if (visited.contains(u))
return u;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
if (edgelist.containsKey(e)) {
long w = edgelist.get(e);
edgelist.put(e, w + weight);
}
else
edgelist.put(e, weight);
return update_value2(p, weight);
}
static void update_finish(long u, long weight) {
if (u == 1)
return;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
long w = edgelist.get(e);
edgelist.put(e, w - weight);
update_finish(p, weight);
}
static void path(long u, long v) {
visited = new TreeSet<>();
stop = false;
path_value1(Math.max(u, v), Math.min(u, v));
if (stop)
return;
long c = path_value2(Math.min(u, v));
path_finish(c);
}
static void path_value1(long u, long dist) {
visited.add(u);
if (u == 1)
return;
if (u == dist) {
stop = true;
return;
}
long w = 0;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
if (edgelist.containsKey(e))
w = edgelist.get(e);
ans += w;
path_value1(p, dist);
}
static long path_value2(long u) {
if (visited.contains(u))
return u;
long w = 0;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
if (edgelist.containsKey(e))
w = edgelist.get(e);
ans += w;
return path_value2(p);
}
static void path_finish(long u) {
if (u == 1)
return;
long p = parent(u);
Edge e = new Edge(Math.max(u, p), Math.min(u, p));
long w = 0;
if (edgelist.containsKey(e))
w = edgelist.get(e);
ans -= w;
path_finish(p);
}
static long parent(long node) {
return node >> 1;
}
static class Edge implements Comparable<Edge>{
long u, v;
public Edge(long u, long v) {
this.u = u;
this.v = v;
}
@Override
public int compareTo(Edge o) {
if (u > o.u)
return 1;
if (u < o.u)
return -1;
if (v > o.v)
return 1;
if (v < o.v)
return -1;
return 0;
}
@Override
public String toString() {
return "(" + u + ", " + v + ")";
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean Ready() throws IOException {
return br.ready();
}
public void waitForInput(long time) {
long ct = System.currentTimeMillis();
while(System.currentTimeMillis() - ct < time) {};
}
}
}
| 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 | 81fa9d5a543dfa8eb4d28f7937c08b19 | train_002.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.*;
import java.io.*;
import java.math.*;
public class Main1
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
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 s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
static HashMap<String,Long> hm=new HashMap<>();
static long v;
public static void dfs(long u,long v,long weight)
{
if(u==v)
return ;
if(v>u)
{
hm.put(v+"#"+(v/2),hm.getOrDefault(v+"#"+(v/2),0l)+weight);
dfs(u,v/2,weight);
}
else
{
hm.put(u+"#"+(u/2),hm.getOrDefault(u+"#"+(u/2),0l)+weight);
dfs(u/2,v,weight);
}
}
public static long dfs1(long u,long v)
{
if(u==v)
return 0;
if(v>u)
return hm.getOrDefault(v+"#"+v/2,0l)+dfs1(u,v/2);
else
return hm.getOrDefault(u+"#"+u/2,0l)+dfs1(u/2,v);
}
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int t=sc.i();
while(t-->0)
{
int q=sc.i();
if(q==1)
dfs(sc.l(),sc.l(),sc.l());
else
{
long node1=sc.l();
long node2=sc.l();
out.println(dfs1(node1,node2));
}
}
out.flush();
}
} | 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 | 5e0a56b060c4378c7a6ae9fdb4b7cd27 | train_002.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.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.StringTokenizer;
public class A implements Runnable {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok = new StringTokenizer("");
private void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
String fileName = "";
if (ONLINE_JUDGE && fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
try {
if (fileName.isEmpty()) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
} catch (Throwable t) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
}
String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
double readDouble() {
return Double.parseDouble(readString());
}
int[] readIntArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
//new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
new A().run();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
@Override
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
void put(long x, long w, HashMap<Long, Long> map) {
Long cost = map.get(x);
if (cost != null) {
map.put(x, cost + w);
} else {
map.put(x, w);
}
}
int getLevel(long x) {
int power = 0;
while (x > 1) {
power++;
x /= 2;
}
return power;
}
long get(long x, HashMap<Long, Long> map) {
Long cost = map.get(x);
if (cost == null) return 0;
return cost;
}
private void solve() {
int q = readInt();
HashMap<Long, Long> map = new HashMap<>();
while (q-- > 0) {
int type = readInt();
if (type == 1) {
long v = readLong();
long u = readLong();
long w = readLong();
int levelV = getLevel(v);
while (getLevel(u) > levelV) {
put(u, w, map);
u /= 2;
}
int levelU = getLevel(u);
while (getLevel(v) > levelU) {
put(v, w, map);
v /= 2;
}
while (u != v) {
put(u, w, map);
put(v, w, map);
v /= 2;
u /= 2;
}
} else {
long v = readLong();
long u = readLong();
long res = 0;
int levelV = getLevel(v);
while (getLevel(u) > levelV) {
res += get(u, map);
u /= 2;
}
int levelU = getLevel(u);
while (getLevel(v) > levelU) {
res += get(v, map);
v /= 2;
}
while (u != v) {
res += get(u, map);
res += get(v, map);
v /= 2;
u /= 2;
}
out.println(res);
}
}
}
}
| 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 | 50a36ae48ac1a64d9091d32259241dc2 | train_002.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.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class A extends cf {
public static void main(String[] args) {A a=new A();}
public void run(InputReader in, PrintWriter out) {
int q=in.nextInt(),c;
long t,cur,tot;
String v,u,e;
Map<String,Long> hm=new HashMap<String,Long>();
for (int ev=0;ev<q;ev++) {
t=in.nextLong();
cur=in.nextLong();
c=0;
v=Long.toBinaryString(cur);
u=Long.toBinaryString(in.nextLong());
while (c<v.length()&&c<u.length()&&v.charAt(c)==u.charAt(c)) {
c++;
}
if (t==1) {
int w=in.nextInt();
for (int i=v.length()-1;i>=c;i--) {
e=cur+" "+(cur/2);
hm.put(e,hm.getOrDefault(e,0L)+w);
cur/=2;
}
for (int i=c;i<u.length();i++) {
if (u.charAt(i)=='0') {
e=(2*cur)+" "+cur;
hm.put(e,hm.getOrDefault(e,0L)+w);
cur*=2;
}
else {
e=(2*cur+1)+" "+cur;
hm.put(e,hm.getOrDefault(e,0L)+w);
cur=2*cur+1;
}
}
}
else {
tot=0;
for (int i=v.length()-1;i>=c;i--) {
e=cur+" "+(cur/2);
tot+=hm.getOrDefault(e,0L);
cur/=2;
}
for (int i=c;i<u.length();i++) {
if (u.charAt(i)=='0') {
e=(2*cur)+" "+cur;
cur*=2;
}
else {
e=(2*cur+1)+" "+cur;
cur=2*cur+1;
}
tot+=hm.getOrDefault(e,0L);
}
out.println(tot);
}
}
}
}
class cf {
public cf() {
try {
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
//InputStream inputStream=new FileInputStream("file.in");
//OutputStream outputStream=new FileOutputStream("file.out");
InputReader in=new InputReader(inputStream);
PrintWriter out=new PrintWriter(outputStream);
run(in,out);
out.close();
} catch (Exception e) {
if (e instanceof FileNotFoundException) {System.out.print("File not found.");}
else {e.printStackTrace();}
}
}
public void run(InputReader in,PrintWriter out) {}
}
class InputReader {
private BufferedReader br;
private StringTokenizer st;
public InputReader(InputStream stream) {
br=new BufferedReader(new InputStreamReader(stream),32768);
st=null;
}
public String next() {
while (st==null||!st.hasMoreTokens()) {
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public int[] nextIntArray(int n) {
int[] a=new int[n];
for (int i=0;i<n;i++) {a[i]=nextInt();}
return a;
}
public long[] nextLongArray(int n) {
long[] a=new long[n];
for (int i=0;i<n;i++) {a[i]=nextLong();}
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 | 3237b562ac8c417fcacc39b3530fc577 | train_002.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.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
// this is not good for reading double values.
public class Problem696A {
static long m = 100000007;
public static void main(String[] args) throws IOException {
Reader r = new Reader();
PrintWriter o = new PrintWriter(System.out, false);
int T = r.nextInt();
HashMap<Long, Long> map = new HashMap<>();
while (T-- > 0) {
int x = r.nextInt();
if (x == 1) {
long v = r.nextLong();
long u = r.nextLong();
long w = r.nextLong();
long lca = getLCA(v, u);
while (v != lca) {
if (map.containsKey(v)) {
map.put(v, map.get(v) + w);
} else {
map.put(v, w);
}
v /= 2;
}
while (u != lca) {
if (map.containsKey(u)) {
map.put(u, map.get(u) + w);
} else {
map.put(u, w);
}
u /= 2;
}
} else {
long v = r.nextLong();
long u = r.nextLong();
long sum = 0;
long lca = getLCA(v, u);
while (v != lca) {
if (map.containsKey(v))
sum += map.get(v);
v /= 2;
}
while (u != lca) {
if (map.containsKey(u))
sum += map.get(u);
u /= 2;
}
o.println(sum);
}
}
o.close();
}
private static long getLCA(long v, long u) {
ArrayList<Long> a = new ArrayList<>();
ArrayList<Long> b = new ArrayList<>();
while (v > 0) {
a.add(v);
v /= 2;
}
while (u > 0) {
b.add(u);
u /= 2;
}
Collections.reverse(a);
Collections.reverse(b);
long res = -1;
for (int i = 0; i < a.size() && i < b.size(); i++) {
if (a.get(i).equals(b.get(i))) {
res = a.get(i);
}
}
return res;
}
// pair object x,y
static class pair {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pair other = (pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
int x, y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
// gcd int no
static int gcd(int n, int r) {
return r == 0 ? n : gcd(r, n % r);
}
static long[][] modPow(long[][] M, long exp) {
long[][] result = new long[][] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
long[][] pow = M;
while (exp != 0) {
if ((exp & 1) == 1) {
result = multiply(result, pow);
}
exp >>>= 1;
pow = multiply(pow, pow);
}
return result;
}
static long[][] multiply(long[][] A, long[][] B) {
long[][] C = new long[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
long value = 0;
for (int k = 0; k < 4; k++) {
value += A[i][k] * B[k][j];
}
C[i][j] = value % m;
}
}
return C;
}
// gcd long numbers
static long gcd(long n, long r) {
return r == 0 ? n : gcd(r, n % r);
}
// input/output
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 final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int size) throws IOException {
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public long[] readLongArray(int size) throws IOException {
long[] arr = new long[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| Java | ["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 | fd5e3724ebe37cbff447602fb5b5efd1 | train_002.jsonl | 1477922700 | There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2; the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2; the second monster can't eat the fifth monster because they are not neighbors; the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other. | 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.Random;
import java.util.StringTokenizer;
public class Solution{
static PrintWriter out = new PrintWriter(System.out);
static int curn;
static int[] a;
static int n;
static StringBuilder str = new StringBuilder("");
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int tt = 1;
while(tt-->0) {
n = fs.nextInt();
a = fs.readArray(n);
curn = n;
int k = fs.nextInt();
int[] b = fs.readArray(k);
int i=0;
for(int j=0;j<k;j++) {
int sum = 0;
int start = i;
while(i<n) {
sum += a[i];
i++;
if(sum==b[j]) break;
}
if(sum!=b[j]) {
out.println("NO");
out.flush();
return;
}
print(a, start, i-1);
}
if(i!=n) {
out.println("NO");
out.flush();
return;
}
out.println("YES");
out.println(str.toString());
}
out.close();
}
static void print(int[] arr, int p, int q) {
int max = 0;
for(int i=p;i<=q;i++) max = Math.max(max, a[i]);
if(p==q) return;
for(int i=p;i<q;i++) {
if(a[i]==max && a[i+1]!=max) {
int l = 0;
for(int k=0;k<q-i;k++) {
str.append(i-(n-curn)+1+" R\n");
}
for(int k=0;k<i-p;k++) {
str.append(i-(n-curn)-l+1+" L\n");
l++;
}
curn = curn - (q-p);
return;
}
}
for(int i=p+1;i<=q;i++) {
if(a[i]==max && a[i-1]!=max) {
int l = 0;
for(int k=0;k<i-p;k++) {
str.append(i-(n-curn)-l+1+" L\n");
l++;
}
for(int k=0;k<q-i;k++) {
str.append(i-(n-curn)-l+1+" R\n");
}
curn = curn - (q-p);
return;
}
}
out.println("NO");
out.flush();
System.exit(0);
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
} | Java | ["6\n1 2 2 2 1 2\n2\n5 5", "5\n1 2 3 4 5\n1\n15", "5\n1 1 1 3 3\n3\n2 1 6"] | 1 second | ["YES\n2 L\n1 R\n4 L\n3 L", "YES\n5 L\n4 L\n3 L\n2 L", "NO"] | NoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue: the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2]; the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2]; the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3]; the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"two pointers",
"greedy"
] | a37f805292e68bc0ad4555fa32d180ef | The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters. The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke. The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end. | 1,800 | In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line. Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them. | standard output | |
PASSED | 253101efde62529e09c1d65783791a77 | train_002.jsonl | 1477922700 | There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2; the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2; the second monster can't eat the fifth monster because they are not neighbors; the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class d {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));;
public static void main(String[] args) throws IOException {
// Scanner s = new Scanner(System.in);
// String[] st=s.readLine().trim().split("\\s+");
// a[i]=Integer.parseInt(st[i]);
// Integer.parseInt(s.readLine().trim().split("\\s+");
StringBuilder sb = new StringBuilder();
StringBuilder sbf = new StringBuilder();
// int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]);
/* String[] st=s.readLine().trim().split("\\s+");
int n=Integer.parseInt(st[0]);*/
String[] s1=si();
int n=ic(s1[0]);
String[] s2=si();
long[] a=new long[n];
for(int i=0;i<n;i++){
a[i]=ic(s2[i]);
}
String[] s3=si();
int m=ic(s3[0]);
long[] b=new long[m];
String[] s4=si();
for(int i=0;i<m;i++){
b[i]=ic(s4[i]);
}long sum=0;int j=0;int flag=0;int x=0;
for(int i=0;i<n;i++){sum=0;
if(j==b.length) {flag=1;break;}
int k=i;
while(i<n&&sum!=b[j]){
sum+=a[i];i++;
}
if(i==n&&sum!=b[j]) {
flag=1;break;
}else j++;
i--;
// System.out.println("HI");
/* if(i==5){
System.out.println(sum+" "+i+" HI");
}*/
if(i==k){
continue;
}
// System.out.println(i+" "+k+" "+sum);
long max=0;int mi=-1;
if(k+1<=i&&a[k+1]<max) mi=k;
for(int l=k;l<=i;l++){
if(a[l]>max&&l<i&&a[l+1]<a[l]){
max=a[l];mi=l;
}else if(a[l]>max&&l>k&&a[l-1]<a[l]){
max=a[l];mi=l;
}
}
if(mi==-1){
// System.out.println("HI");
flag=1;break;
}
int left=mi;int right=mi;
if(left>k&&a[left-1]<a[left]){
while(left>k){
sb.append((left-x+1)+" L\n");left--;
}
while(right<i){
sb.append((left-x+1)+" R\n");right++;
}
}else{
while(right<i){
sb.append((left-x+1)+" R\n");right++;
}
while(left>k){
sb.append((left-x+1)+" L\n");left--;
}
}
x+=(i-k);
}if(flag==1||j<m){
System.out.println("NO");
// System.out.println(sb.toString());
}else{
System.out.println("YES");
System.out.println(sb.toString());
}
}
static String[] si()throws IOException{
return s.readLine().trim().split("\\s+");
}
static int ic(String ss){
return Integer.parseInt(ss);
}
static String lexographicallysmallest(String s) {
if (s.length() % 2 == 1) return s;
String s1 =lexographicallysmallest(s.substring(0, s.length()/2));
String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length()));
if (s1.compareTo(s2)<0) return s1 + s2;
else return s2 + s1;
}
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}
static int[] BitsSetTable256 ;
public static void initialize(int n)
{
BitsSetTable256[0] = 0;
for (int i = 0; i <=Math.pow(2,n); i++) {
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}
static void dfs(int i,int val,ArrayList<Integer>[] adj){
}
static void computeLPSArray(String pat, int M, int lps[]) {
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0) {
len = lps[len - 1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long powerwithmod(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long powerwithoutmod(long x, int y) {
long temp;
if( y == 0)
return 1;
temp = powerwithoutmod(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
static void fracion(double x) {
String a = "" + x;
String spilts[] = a.split("\\."); // split using decimal
int b = spilts[1].length(); // find the decimal length
int denominator = (int) Math.pow(10, b); // calculate the denominator
int numerator = (int) (x * denominator); // calculate the nerumrator Ex
// 1.2*10 = 12
int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common
// divisor bw them
String fraction = "" + numerator / gcd + "/" + denominator / gcd;
// System.out.println((denominator/gcd));
long x1 = modInverse(denominator / gcd, 998244353);
// System.out.println(x1);
System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353));
}
static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(i1);Queue<Integer> aq=new LinkedList<Integer>();
aq.add(0);
while(!q.isEmpty()){
int i=q.poll();
int val=aq.poll();
if(i==n){
return val;
}
if(h[i]!=null){
for(Integer j:h[i]){
if(vis[j]==0){
q.add(j);vis[j]=1;
aq.add(val+1);}
}
}
}return -1;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long modInverse(long a, long m)
{
return (powerwithmod(a, m - 2, m));
}
static int MAXN;
static int[] spf;
static void sieve() {
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
static ArrayList<Integer> getFactorizationUsingSeive(int x) {
ArrayList<Integer> ret = new ArrayList<Integer>();
while (x != 1)
{
ret.add(spf[x]);
if(spf[x]!=0) x = x / spf[x];
else break; }
return ret;
}
static long[] fac ;
static void calculatefac(long mod){
fac[0]=1;
for (int i = 1 ;i <= MAXN; i++)
fac[i] = fac[i-1] * i % mod;
}
static long nCrModPFermat(int n, int r, long mod) {
if (r == 0)
return 1;
fac[0] = 1;
return (fac[n]*
modInverse(fac[r], mod)
% mod * modInverse(fac[n-r], mod)
% mod) % mod;
} }
class Student {
int l;long r;
public Student(int l, long r) {
this.l = l;
this.r = r;
}
public String toString()
{
return this.l+" ";
}
}
class Sortbyroll implements Comparator<Student>
{
public int compare(Student a, Student b){
if(a.r<b.r) return -1;
else if(a.r==b.r){
if(a.r==b.r){
return 0;
}
if(a.r<b.r) return -1;
return 1;}
return 1; }
}
class Sortbyroll2 implements Comparator<Student>
{
public int compare(Student a, Student b){
try{
if(a.l*b.r<b.l*a.r) return 1;
return -1;}
catch (IllegalArgumentException e){
System.out.println("HI");
}
return 9;}
} | Java | ["6\n1 2 2 2 1 2\n2\n5 5", "5\n1 2 3 4 5\n1\n15", "5\n1 1 1 3 3\n3\n2 1 6"] | 1 second | ["YES\n2 L\n1 R\n4 L\n3 L", "YES\n5 L\n4 L\n3 L\n2 L", "NO"] | NoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue: the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2]; the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2]; the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3]; the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue. | Java 11 | standard input | [
"dp",
"constructive algorithms",
"two pointers",
"greedy"
] | a37f805292e68bc0ad4555fa32d180ef | The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters. The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke. The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end. | 1,800 | In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line. Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them. | standard output | |
PASSED | fc4d6e0aa4aa3b4cf9c0af4fdaf4c408 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
final static int MAXN = (int)(3 * 1e4);
MaxFlowMinCost mfmc;
Set<Integer> []g;
boolean []used;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean prime[] = new boolean[MAXN];
Arrays.fill(prime, true);
for(int i = 2; i < MAXN; ++i) {
if (prime[i]) {
if (1L * i * i >= MAXN) continue;
for(int j = i * i; j < MAXN; j += i) {
prime[j] = false;
}
}
}
// for(int i = 2; i < 100; ++i) {
// if (prime[i]) {
// System.out.println(i);
// }
// }
int n = nextInt();
int []a = new int[n];
for(int i = 0; i < n; ++i) a[i] = nextInt();
int source = n, sink = n + 1;
mfmc = new MaxFlowMinCost(n + 2, source, sink);
for(int i = 0; i < n; ++i) {
if (a[i] % 2 == 0) {
mfmc.addEdge(source, i, 2);
}else {
mfmc.addEdge(i, sink, 2);
}
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if (prime[a[i] + a[j]]) {
if (a[i] % 2 == 0) {
mfmc.addEdge(i, j, 1);
}
}
}
}
mfmc.execute();
if (mfmc.flow != n) {
out.println("Impossible");
out.close();
return;
}
g = new HashSet[n];
for(int i = 0; i < n; ++i) g[i] = new HashSet<>();
for(Edge e : mfmc.e) {
// System.out.println(e);
if (e.cap != e.flow || e.back) continue;
if (e.from == source || e.to == source) continue;
if (e.from == sink || e.to == sink) continue;
int v = e.from, u = e.to;
g[v].add(u);
g[u].add(v);
}
// for(int i = 0; i < n; ++i) {
// System.out.print(i + "-> ");
// for(int j : g[i]) {
// System.out.print(j + " ");
// }
// System.out.println();
// }
List<Integer> path = new ArrayList<>();
int cmp = 0;
used = new boolean[n];
for(int i = 0; i < n; ++i) {
if (!used[i]) {
++cmp;
path.clear();
euler(i, path);
out.print(path.size() + " ");
for(int j : path) {
used[j] = true;
out.print((j+1) + " ");
}
out.println();
}
}
System.out.println(cmp);
out.close();
}
private void euler(int x, List<Integer> path) {
Stack<Integer> stack = new Stack<Integer>();
stack.add(x);
while(stack.size() > 0) {
int v = stack.peek();
if (g[v].size() == 0) {
path.add(v);
stack.pop();
}else {
Iterator<Integer> it = g[v].iterator();
int u = it.next();
g[v].remove(u);
g[u].remove(v);
stack.add(u);
}
}
path.remove(path.size()-1);
}
class Edge {
int from, to, cap, flow;
boolean back;
public Edge(int from, int to, int cap, int flow) {
this.from = from;
this.to = to;
this.cap = cap;
this.flow = flow;
this.back = false;
if (cap == flow) this.back = true;
}
public String toString() {
return "[ from=" + from + ", to=" + to + ", cap=" + cap + ", flow=" + flow + " ]";
}
}
final static int oo = Integer.MAX_VALUE / 2;
class MaxFlowMinCost {
int n, source, sink;
List<Integer> []g;
List<Edge> e;
int []ptr, q, d;
boolean []inqueue;
int flow;
public MaxFlowMinCost(int n, int source, int sink) {
this.n = n;
this.source = source;
this.sink = sink;
g = new ArrayList[n];
for(int i = 0; i < n; ++i) g[i] = new ArrayList<>();
e = new ArrayList<Edge>();
ptr = new int[n];
q = new int[n];
d = new int[n];
inqueue = new boolean[n];
}
public void execute() {
while(bfs()) {
Arrays.fill(ptr, 0);
while(true) {
int pushed = dfs(source, oo);
if (pushed == 0) break;
flow += pushed;
}
}
}
private int dfs(int v, int flow) {
if (flow == 0) return 0;
if (v == sink) return flow;
for(;ptr[v] < g[v].size(); ++ptr[v]) {
int id = g[v].get(ptr[v]);
Edge edge = e.get(id);
if (d[edge.to] != d[v] + 1) continue;
int pushed = dfs(edge.to, Math.min(flow, edge.cap - edge.flow));
if (pushed > 0) {
e.get(id).flow += pushed;
e.get(id ^ 1).flow -= pushed;
return pushed;
}
}
return 0;
}
private boolean bfs(){
Arrays.fill(inqueue, false);
Arrays.fill(d, oo);
d[source] = 0;
inqueue[source] = true;
int head = 0, tail = 0;
q[tail++] = source;
while(head != tail && d[sink] == oo) {
int v = q[head++];
for(int id : g[v]) {
Edge edge = e.get(id);
if (edge.cap == edge.flow) continue;
if (d[edge.to] > d[v] + 1) {
d[edge.to] = d[v] + 1;
if (inqueue[edge.to]) continue;
inqueue[edge.to] = true;
q[tail++] = edge.to;
if (tail == n) tail = 0;
}
}
if (head == n) head = 0;
inqueue[v] = false;
}
return d[sink] != oo;
}
public void addEdge(int from, int to, int cap) {
g[from].add(e.size());
e.add(new Edge(from, to, cap, 0));
g[to].add(e.size());
e.add(new Edge(to, from, cap, cap));
}
}
public static void main(String args[]) throws Exception{
new Main().run();
}
} | Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 10779a1350c3679cb67521111b15ed55 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class c {
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
boolean[] prime = new boolean[100001];
Arrays.fill(prime, true);
for(int i = 2; i<prime.length; i++)
{
if(!prime[i]) continue;
for(long j = (long)i*i; j < prime.length; j+=i)
{
prime[(int)j] = false;
}
}
int n = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++) data[i] = input.nextInt();
TidalFlow tf = new TidalFlow(n);
for(int i = 0; i<n; i++)
{
if(data[i]%2 == 0) tf.add(tf.s, i, 2);
else tf.add(i, tf.t, 2);
for(int j = i+1; j<n; j++)
{
if(prime[data[i] + data[j]])
{
if(data[i]%2 == 0)
{
tf.add(i, j, 1);
}
else
{
tf.add(j, i, 1);
}
}
}
}
int flow = tf.getFlow();
if(flow == n)
{
int[][] adjs = new int[n][2];
int[] ptrs = new int[n];
for(ArrayList<TidalFlow.Edge> list : tf.adj)
{
for(TidalFlow.Edge e : list)
{
if(e.flow == 1)
{
adjs[e.i][ptrs[e.i]++] = e.j;
adjs[e.j][ptrs[e.j]++] = e.i;
}
}
}
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
boolean[] used = new boolean[n];
for(int i = 0; i<n; i++)
{
if(used[i]) continue;
ArrayList<Integer> toAdd = new ArrayList<Integer>();
int at = i;
int last = adjs[at][1];
while(true)
{
int temp = last;
last = at;
at = adjs[at][0] == temp ? adjs[at][1] : adjs[at][0];
used[at] = true;
toAdd.add(at);
if(at == i) break;
}
res.add(toAdd);
}
out.println(res.size());
for(int i = 0; i<res.size(); i++)
{
out.print(res.get(i).size());
for(int x : res.get(i))
out.print(" "+(1+x));
out.println();
}
}
else
{
out.println("Impossible");
}
out.close();
}
static class TidalFlow {
ArrayDeque<Edge> stk = new ArrayDeque<Edge>();
int N, s, t, oo = 987654321, fptr, bptr;
ArrayList<Edge>[] adj;
int[] q, dist, pool;
@SuppressWarnings("unchecked")
TidalFlow(int NN) {
N=(t=(s=NN)+1)+1;
adj = new ArrayList[N];
for(int i = 0; i < N; adj[i++] = new ArrayList<Edge>());
dist = new int[N];
pool = new int[N];
q = new int[N];
}
void add(int i, int j, int cap) {
Edge fwd = new Edge(i, j, cap, 0);
Edge rev = new Edge(j, i, 0, 0);
adj[i].add(rev.rev=fwd);
adj[j].add(fwd.rev=rev);
}
int augment() {
Arrays.fill(dist, Integer.MAX_VALUE);
pool[t] = dist[s] = fptr = bptr = 0;
pool[q[bptr++] = s] = oo;
while(bptr > fptr && q[fptr] != t)
for(Edge e : adj[q[fptr++]]) {
if(dist[e.i] < dist[e.j])
pool[e.j] += e.carry = Math.min(e.cap - e.flow, pool[e.i]);
if(dist[e.i] + 1 < dist[e.j] && e.cap > e.flow)
dist[q[bptr++] = e.j] = dist[e.i] + 1;
}
if(pool[t] == 0) return 0;
Arrays.fill(pool, fptr = bptr = 0);
pool[q[bptr++] = t] = oo;
while(bptr > fptr)
for(Edge e : adj[q[fptr++]]) {
if(pool[e.i] == 0) break;
int f = e.rev.carry = Math.min(pool[e.i], e.rev.carry);
if(dist[e.i] > dist[e.j] && f != 0) {
if(pool[e.j] == 0) q[bptr++] = e.j;
pool[e.i] -= f;
pool[e.j] += f;
stk.push(e.rev);
}
}
int res = pool[s];
Arrays.fill(pool, 0);
pool[s] = res;
while(stk.size() > 0) {
Edge e = stk.pop();
int f = Math.min(e.carry, pool[e.i]);
pool[e.i] -= f;
pool[e.j] += f;
e.flow += f;
e.rev.flow -= f;
}
return res;
}
int getFlow() {
int res = 0, f = 1;
while(f != 0)
res += f = augment();
return res;
}
class Edge {
int i, j, cap, flow, carry;
Edge rev;
Edge(int ii, int jj, int cc, int ff) {
i=ii; j=jj; cap=cc; flow=ff;
}
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 3caf6949c71948a76454f18d3958e83e | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.util.*;
public class CF510E_FoxAndDinner {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int size = (int) (10e4*2+10);
boolean[] primes = new boolean[size];
Arrays.fill(primes, true);
for(int i = 2; i < size; i ++){
if(!primes[i])continue;
for(int j = i * 2; j < size; j += i){
primes[j] = false;
}
}
// for(int i = 0; i < 30; i ++)System.out.print(primes[i] + ", ");
int[] v = new int[n];
int ctr = 0;
for(int i = 0; i < n; i ++){
v[i] = in.nextInt();
ctr+=v[i]%2;
}
if(ctr != n - ctr){
System.out.println("Impossible");
return;
}
TidalFlow flow = new TidalFlow(n);
for(int i = 0; i < n; i ++){
if(v[i] % 2 != 0) continue;
for(int j = 0; j < n; j ++){
if(primes[v[i] + v[j]]){
flow.add(i, j, 1);
}
}
}
//source, sink
for(int i = 0; i < n; i ++){
if(v[i] % 2 == 0) flow.add(flow.s, i, 2);
else flow.add(i, flow.t, 2);
}
// System.out.println(flow.getFlow());
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; i ++)adj[i] = new ArrayList<Integer>();
if(flow.getFlow() != n){
System.out.println("Impossible");
return;
}
for(ArrayList<TidalFlow.Edge> ee: flow.adj){
for(TidalFlow.Edge e: ee){
if(e.i == flow.s || e.j == flow.t)continue;
if(e.flow == 1){
adj[e.i].add(e.j);
adj[e.j].add(e.i);
}
}
}
// for(int i = 0; i < n; i ++)System.out.println(adj[i]);
boolean[] vis = new boolean[n];
ArrayList<String> ans = new ArrayList<String>();
for(int i = 0; i < n; i ++){
if(vis[i]) continue;
int at = i;
vis[at] = true;
String add = "" + (i + 1);
int len = 0;
while(true){
len++;
int to = -1;
for(int e: adj[at]){
if(!vis[e]){
to = e;
}
}
if(to == -1) break;
vis[to] = true;
at = 2;
add += " " + (to + 1);
at = to;
}
add = len + " " + add;
ans.add(add);
}
System.out.println(ans.size());
for(String e: ans)System.out.println(e);
}
static class TidalFlow {
ArrayDeque<Edge> stk = new ArrayDeque<Edge>();
int N, s, t, oo = 987654321, fptr, bptr;
ArrayList<Edge>[] adj;
int[] q, dist, pool;
@SuppressWarnings("unchecked")
TidalFlow(int NN) {
N=(t=(s=NN)+1)+1;
adj = new ArrayList[N];
for(int i = 0; i < N; adj[i++] = new ArrayList<Edge>());
dist = new int[N];
pool = new int[N];
q = new int[N];
}
void add(int i, int j, int cap) {
Edge fwd = new Edge(i, j, cap, 0);
Edge rev = new Edge(j, i, 0, 0);
adj[i].add(rev.rev=fwd);
adj[j].add(fwd.rev=rev);
}
int augment() {
Arrays.fill(dist, Integer.MAX_VALUE);
pool[t] = dist[s] = fptr = bptr = 0;
pool[q[bptr++] = s] = oo;
while(bptr > fptr && q[fptr] != t)
for(Edge e : adj[q[fptr++]]) {
if(dist[e.i] < dist[e.j])
pool[e.j] += e.carry = Math.min(e.cap - e.flow, pool[e.i]);
if(dist[e.i] + 1 < dist[e.j] && e.cap > e.flow)
dist[q[bptr++] = e.j] = dist[e.i] + 1;
}
if(pool[t] == 0) return 0;
Arrays.fill(pool, fptr = bptr = 0);
pool[q[bptr++] = t] = oo;
while(bptr > fptr)
for(Edge e : adj[q[fptr++]]) {
if(pool[e.i] == 0) break;
int f = e.rev.carry = Math.min(pool[e.i], e.rev.carry);
if(dist[e.i] > dist[e.j] && f != 0) {
if(pool[e.j] == 0) q[bptr++] = e.j;
pool[e.i] -= f;
pool[e.j] += f;
stk.push(e.rev);
}
}
int res = pool[s];
Arrays.fill(pool, 0);
pool[s] = res;
while(stk.size() > 0) {
Edge e = stk.pop();
int f = Math.min(e.carry, pool[e.i]);
pool[e.i] -= f;
pool[e.j] += f;
e.flow += f;
e.rev.flow -= f;
}
return res;
}
int getFlow() {
int res = 0, f = 1;
while(f != 0)
res += f = augment();
return res;
}
class Edge {
int i, j, cap, flow, carry;
Edge rev;
Edge(int ii, int jj, int cc, int ff) {
i=ii; j=jj; cap=cc; flow=ff;
}
}
}
}
| Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 04554dd8d7a854d8588f7fa4fcc463c6 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | // package Div2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Sketch {
// Dinic algorithm
public static final int INF = 100000000;
public static final int NMAX = 100000;
public static class Edge {
public int next;
public int flow;
public int rev;
public Edge(int next, int flow, int rev){
this.next = next;
this.flow = flow;
this.rev = rev;
}
}
public static Edge[] edges = new Edge[2*NMAX];
public static int[] edgeList = new int[2*NMAX];
public static int[] starts = new int[2*NMAX];
public static int[] levels = new int[2*NMAX];
public static int listEnd = 0;
public static int N = 0;
static {
for(int i=0; i<2*NMAX; i++){
edgeList[i] = -1;
starts[i] = -1;
}
}
public static void addEdge(int u, int v, int cap){
edges[listEnd] = new Edge(v, cap, listEnd+1);
edgeList[listEnd] = starts[u];
starts[u] = listEnd++;
edges[listEnd] = new Edge(u, 0, listEnd-1);
edgeList[listEnd] = starts[v];
starts[v] = listEnd++;
}
private static boolean mkLevel(){
for(int i=0; i<N+2; i++){
levels[i] = -1;
}
levels[0] = 0;
List<Integer> list = new LinkedList<Integer>();
list.add(0);
while(list.size()!=0){
int item = list.get(0);
list.remove(0);
if(item == N+1)
continue;
for(int t=starts[item]; t!=-1; t=edgeList[t]){
if(edges[t].flow>0 && levels[edges[t].next] == -1){
levels[edges[t].next] = levels[item]+1;
list.add(edges[t].next);
}
}
}
return levels[N+1]!=-1;
}
private static int extend(int start, int cap){
if(start == N+1){
return cap;
}
int ret = 0;
for(int t=starts[start]; t!=-1; t=edgeList[t]){
if(edges[t].flow > 0 && levels[edges[t].next] == levels[start]+1){
int fl = edges[t].flow;
if(fl > cap-ret)
fl = cap-ret;
int r = extend(edges[t].next, fl);
edges[t].flow -= r;
edges[edges[t].rev].flow += r;
ret += r;
}
}
if(ret==0)
levels[start] = -1;
return ret;
}
public static int flow(){
int ret = 0;
int r = 0;
while(mkLevel()){
while((r = extend(0, INF)) > 0){
ret += r;
}
}
return ret;
}
public static boolean isPrime(int n){
if(n <= 1)
return false;
if(n == 2)
return true;
int sqt = (int) Math.sqrt(n);
for(int i=2; i<=sqt; i++){
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
N = input.nextInt();
int[] ages = new int[N];
for(int i=0; i<N; i++){
ages[i] = input.nextInt();
}
input.close();
for(int i=0; i<N; i++){
if(ages[i]%2==0)
addEdge(0, i+1, 2);
else
addEdge(i+1, N+1, 2);
}
for(int i=0; i<N-1; i++){
for(int j=i+1; j<N; j++){
if(isPrime(ages[i] + ages[j])){
if(ages[i]%2==0){
addEdge(i+1, j+1, 1);
}
else
addEdge(j+1, i+1, 1);
}
}
}
if(flow()==N){
List<int[]> partition = new ArrayList<int[]>();
boolean[] used = new boolean[N+1];
for(int i=1; i<=N; i++){
if(!used[i]){
int[] buf = new int[N];
buf[0] = i;
used[i] = true;
int tail = 1;
int cur = 0;
while(cur<tail){
int item = buf[cur];
cur++;
for(int t=starts[item]; t!=-1; t=edgeList[t]){
int nxt = edges[t].next;
if(nxt>0 && nxt <=N && (ages[item-1]%2==0 && edges[t].flow==0 || ages[item-1]%2==1 && edges[t].flow==1)
&& !used[nxt]){
buf[tail++] = nxt;
used[nxt] = true;
break;
}
}
}
int[] tbl = new int[tail];
for(int j=0; j<tail; j++)
tbl[j] = buf[j];
partition.add(tbl);
}
}
System.out.println(partition.size());
for(int i=0; i<partition.size(); i++){
int[] tmp = partition.get(i);
System.out.print(tmp.length + " ");
for(int j=0; j<tmp.length; j++){
System.out.print(tmp[j] + " ");
}
System.out.println();
}
}
else
System.out.println("Impossible");
}
}
| Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 9ff28c4cf86fd11b4476d9e143df2ac8 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 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 E_Round_290_Div2 {
public static long MOD = 1000000007;
static int[] w, l;
static int min;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
w = new int[n];
l = new int[n];
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
if (data[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
HashSet<Integer> set = new HashSet();
boolean[] p = new boolean[100000];
for (int i = 2; i < p.length; i++) {
if (!p[i]) {
set.add(i);
for (int j = i + i; j < p.length; j += i) {
p[j] = true;
}
}
}
boolean[][] map = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (set.contains(data[i] + data[j])) {
map[i][j] = true;
map[j][i] = true;
}
}
}
int[][] flow = new int[n + 2][n + 2];
for (int i = 0; i < n; i++) {
if (data[i] % 2 == 0) {
flow[0][i + 1] = 2;
} else {
flow[i + 1][n + 1] = 2;
}
}
for (int i = 0; i < n; i++) {
if (data[i] % 2 == 0) {
for (int j = 0; j < n; j++) {
if (map[i][j]) {
flow[i + 1][j + 1] = 1;
}
}
}
}
int result = 0;
while (true) {
int[] pa = new int[n + 2];
Arrays.fill(pa, -1);
LinkedList<Integer> q = new LinkedList();
q.add(0);
pa[0] = 0;
while (!q.isEmpty()) {
int node = q.poll();
for (int i = 1; i < flow.length; i++) {
if (flow[node][i] > 0 && pa[i] == -1) {
q.add(i);
pa[i] = node;
}
}
}
//System.out.println(Arrays.toString(pa));
if (pa[n + 1] == -1) {
break;
}
min = Integer.MAX_VALUE;
flow(n + 1, pa, flow);
result += min;
}
//System.out.println(result);
if (result == n) {
boolean[][] tmp = new boolean[n][n];
for (int i = 0; i < n; i++) {
if (data[i] % 2 == 0) {
for (int j = 0; j < n; j++) {
if (map[i][j] && flow[i + 1][j + 1] == 0) {
tmp[i][j] = true;
tmp[j][i] = true;
}
}
}
}
ArrayList<ArrayList<Integer>> re = new ArrayList();
boolean[] check = new boolean[n];
for (int i = 0; i < n; i++) {
if (!check[i] && data[i] % 2 == 0) {
check[i] = true;
ArrayList<Integer> list = new ArrayList();
dfs(i, list, check, tmp);
re.add(list);
}
}
out.println(re.size());
for (ArrayList<Integer> list : re) {
out.print(list.size() + " ");
for (int i : list) {
out.print((i + 1) + " ");
}
out.println();
}
} else {
out.println("Impossible");
}
out.close();
}
static void dfs(int node, ArrayList<Integer> list, boolean[] check, boolean[][] map) {
check[node] = true;
list.add(node);
for (int i = 0; i < map.length; i++) {
if (map[node][i] && !check[i]) {
dfs(i, list, check, map);
}
}
}
static void flow(int node, int[] pa, int[][] flow) {
if (pa[node] != node) {
min = Math.min(min, flow[pa[node]][node]);
flow(pa[node], pa, flow);
flow[pa[node]][node] -= min;
flow[node][pa[node]] += min;
}
}
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 x - o.x;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
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 | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | b49c7c33a5179562406478bb4b949cb2 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CF_510E {
public static void main(String[] args) throws IOException {
new CF_510E().solve();
}
int[] findPath(int[][]resid, int src, int sink){
int[] from=new int[resid.length];
Arrays.fill(from, -1);
boolean[] visited=new boolean[resid.length];
ArrayDeque<Integer> q=new ArrayDeque<>();
q.add(src);
visited[src]=true;
while (!q.isEmpty()){
int where=q.pollFirst();
for (int to=0;to<resid.length;to++)
if (resid[where][to]>0 && !visited[to]){
from[to]=where;
visited[to]=true;
q.add(to);
}
}
if (from[sink]==-1) return null;
return from;
}
int pathBreadth(int[][] resid, int src, int sink, int[] from){
if (from==null) return 0;
int size=-1;//2 max flow along path
for (int where=sink;where!=src;where=from[where]){
int val=resid[from[where]][where];
size= size<0? val : Math.min(val, size);
}
return size;
}
int maxFlow(int[][] resid, int src, int sink){
int[][] inv=new int[resid.length][resid.length];
int[] from;
int flowSize=0;
// System.out.println(Arrays.deepToString(resid));
while ((from=findPath(resid, src, sink))!=null){
int pathSize=pathBreadth(resid, src, sink, from);
flowSize+=pathSize;
for (int where=sink; where!=src;where=from[where]){
resid[where][from[where]]+=pathSize;
resid[from[where]][where]-=pathSize;
}
}
// System.out.println(Arrays.deepToString(resid));
// System.out.println(flowSize);
return flowSize;
}
ArrayList<ArrayList<Integer>> position(int[][] resid){
int n=resid.length-2;
boolean[] visited=new boolean[n];
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
for (int i=0;i<n;i++){
if (visited[i]) continue;
ArrayList<Integer> curr=new ArrayList<Integer>();
int pos=i;
do{
visited[pos]=true;
curr.add(pos);
if (pos<n/2){
for (int j=n/2;j<n;j++)
if(resid[j][pos]==1 && !visited[j]){
pos=j;
break;
}
}
else{
for (int j=0;j<n/2;j++)
if(resid[pos][j]==1 && !visited[j]){
pos=j;
break;
}
}
}while (!visited[pos]);
res.add(curr);
}
return res;
}
boolean isPrime(int n){
for (int i=2;i*i<=n;i++)
if (n%i==0) return false;
return true;
}
void solve() throws IOException{
InputStream in = System.in;
PrintStream out = System.out;
// in = new FileInputStream("in.txt");
// out = new PrintStream("out.txt");
String impossible="Impossible";
Scanner sc=new Scanner(in);
int n=sc.nextInt();
int[] a=new int[n];
ArrayList<Integer> even=new ArrayList<Integer>(),
odd=new ArrayList<Integer>();
int[] oldIndex=new int[2*n];
for (int i=0;i<n;i++){
int val=a[i]=sc.nextInt();
if (val%2==0) {
even.add(val);
oldIndex[even.size()-1]=i;
}
else {
odd.add(val);
oldIndex[n/2+odd.size()-1]=i;
}
}
if (even.size()!=odd.size()) {
out.println(impossible);
return;
}
int[][] graph=new int[n+2][n+2];
int src=graph.length-2, sink=graph.length-1;
for (int i=0;i<n/2;i++)
graph[src][i]=2;
for (int i=0;i<n/2;i++)
graph[n/2+i][sink]=2;
for (int i=0;i<n/2;i++)
for (int j=0;j<n/2;j++){
// if ((new BigInteger((even.get(i)+odd.get(j))+"")).isProbablePrime(1))
if (isPrime(even.get(i)+odd.get(j)))
graph[i][n/2+j]=1;
}
int res=maxFlow(graph, src, sink);
if (res<n){
out.println(impossible);
return;
}
ArrayList<ArrayList<Integer>> ans=position(graph);
out.println(ans.size());
for (ArrayList<Integer> al:ans){
out.print(al.size()+" ");
for (int i=0;i<al.size();i++){
int val=al.get(i);
out.print((oldIndex[val]+1)+" ");
}
out.println();
}
}
} | Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | d672b833beec1d05cbfc5ca08eb4c100 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/*
4
3 4 8 9
5
2 2 2 2 2
12
2 3 4 5 6 7 8 9 10 11 12 13
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
*/
public class e {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
boolean[] composite = composite((int)5E4);
int numFoxes = in.nextInt();
int[] ages = new int[numFoxes];
TidalFlow tf = new TidalFlow(numFoxes*2);
for(int fox1 = 0; fox1 < numFoxes; ++fox1)
{
ages[fox1] = in.nextInt();
for(int fox2 = 0; fox2 < fox1; ++fox2)
{
if(!composite[ages[fox1] + ages[fox2]])
{
//System.out.println("[" +fox1 + "] " +ages[fox1] +", ["+fox2 +"] " +ages[fox2] );
if(ages[fox1] %2 == 0)
tf.add(fox1, fox2 + numFoxes, 1);
else
tf.add(fox2, fox1 + numFoxes, 1);
}
}
tf.add(tf.s, fox1, 2);
tf.add(fox1 + numFoxes, tf.t, 2);
}
in.close();
int flow = tf.getFlow();
//System.out.println(flow);
if(flow == numFoxes)
{
// for(int fox1 = 0; fox1 < numFoxes; ++fox1)
// {
// System.out.println(fox1+1);
// for(Edge e: tf.adj[fox1])
// {
// if(e.j < numFoxes*2)
// {
// System.out.println("("+(e.i+1) +" - " +(e.j- numFoxes +1) +") " +e.carry +" " + e.flow);
// //System.out.println("("+(e.rev.i- numFoxes) +" - " +e.rev.j +") " +e.rev.carry +" " + e.rev.flow);
// }
// }
// System.out.println("Rev:");
// for(Edge e: tf.adj[fox1+numFoxes])
// {
// if(e.j < numFoxes*2)
// {
// System.out.println("("+(e.i+1- numFoxes) +" - " +(e.j +1) +") " +e.carry +" " + e.flow);
// //System.out.println("("+(e.rev.i- numFoxes) +" - " +e.rev.j +") " +e.rev.carry +" " + e.rev.flow);
// }
// }
// System.out.println();
// }
ArrayList<ArrayList<Integer>> tables = new ArrayList<ArrayList<Integer>>();
boolean[] used = new boolean[numFoxes];
for(int fox1 = 0; fox1 < numFoxes; ++fox1)
{
if(used[fox1])
continue;
ArrayDeque<Integer> stk = new ArrayDeque<Integer>();
stk.add(fox1);
ArrayList<Integer> list = new ArrayList<Integer>();
while(!stk.isEmpty())
{
int node = stk.pop();
if(used[node])
continue;
//System.out.println("P: "+node);
used[node] = true;
list.add(node+1);
for(Edge e: tf.adj[node + (ages[node]%2 == 0?0:numFoxes)])
{
int next = e.j - (ages[node]%2 == 1?0:numFoxes);
//System.out.println("N: "+next);
if(next < numFoxes && !used[next] && e.flow != 0)
{
//System.out.println("A: " +next);
stk.push(next);
}
}
}
tables.add(list);
}
System.out.println(tables.size());
for(ArrayList<Integer> list: tables)
{
System.out.print(list.size() + " ");
for(int i = 0; i < list.size(); ++i)
{
int num = list.get(i);
System.out.print(num +" ");
//System.out.print("("+ages[num-1]+") ");
int prime = (ages[num-1]+ages[list.get((i+1)%list.size())-1]);
//System.out.print("("+prime +") ");
if(composite[prime])
prime = 1/0;
}
System.out.println();
}
}
else
{
System.out.println("Impossible");
}
}
public static boolean[] composite(int size)
{
boolean[] composite = new boolean[size+1];
for(int curr = 2; curr*curr < size; ++curr)
{
if(composite[curr])
continue;
for(int curr2 = curr*curr; curr2 < size; curr2 += curr)
composite[curr2] = true;
}
// for(int i = 0; i < 100; ++i)
// {
// System.out.print(i +": "+(composite[i]?1:0) +", ");
// }
// System.out.println();
return composite;
}
static class TidalFlow {
ArrayDeque<Edge> stk = new ArrayDeque<Edge>();
int N, s, t, oo = 987654321, fptr, bptr;
ArrayList<Edge>[] adj;
int[] q, dist, pool;
@SuppressWarnings("unchecked")
TidalFlow(int NN) {
N = (t = (s = NN) + 1) + 1;
adj = new ArrayList[N];
for (int i = 0; i < N; adj[i++] = new ArrayList<Edge>())
;
dist = new int[N];
pool = new int[N];
q = new int[N];
}
void add(int i, int j, int cap) {
Edge fwd = new Edge(i, j, cap, 0);
Edge rev = new Edge(j, i, 0, 0);
adj[i].add(rev.rev = fwd);
adj[j].add(fwd.rev = rev);
}
int augment() {
Arrays.fill(dist, Integer.MAX_VALUE);
pool[t] = dist[s] = fptr = bptr = 0;
pool[q[bptr++] = s] = oo;
while (bptr > fptr && q[fptr] != t)
for (Edge e : adj[q[fptr++]]) {
if (dist[e.i] < dist[e.j])
pool[e.j] += e.carry = Math.min(e.cap - e.flow, pool[e.i]);
if (dist[e.i] + 1 < dist[e.j] && e.cap > e.flow)
dist[q[bptr++] = e.j] = dist[e.i] + 1;
}
if (pool[t] == 0)
return 0;
Arrays.fill(pool, fptr = bptr = 0);
pool[q[bptr++] = t] = oo;
while (bptr > fptr)
for (Edge e : adj[q[fptr++]]) {
if (pool[e.i] == 0)
break;
int f = e.rev.carry = Math.min(pool[e.i], e.rev.carry);
if (dist[e.i] > dist[e.j] && f != 0) {
if (pool[e.j] == 0)
q[bptr++] = e.j;
pool[e.i] -= f;
pool[e.j] += f;
stk.push(e.rev);
}
}
int res = pool[s];
Arrays.fill(pool, 0);
pool[s] = res;
while (stk.size() > 0) {
Edge e = stk.pop();
int f = Math.min(e.carry, pool[e.i]);
pool[e.i] -= f;
pool[e.j] += f;
e.flow += f;
e.rev.flow -= f;
}
return res;
}
int getFlow() {
int res = 0, f = 1;
while (f != 0)
res += f = augment();
return res;
}
}
static class Edge {
int i, j, flow, carry;
private int cap;
Edge rev;
Edge(int ii, int jj, int cc, int ff) {
i = ii;
j = jj;
cap = cc;
flow = ff;
}
}
}
| Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 5126b8a34789e28a3a72df886f04bb7e | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf290E {
static boolean[] primes = new boolean[20010];
public static void main(String[] args) throws Exception {
// BufferedReader in = new BufferedReader(new FileReader("cf290E.in"));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String[] arr = in.readLine().split(" ");
int[] a = new int[arr.length];
for(int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(arr[i]);
}
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for(int i = 2; i < primes.length; i++) {
if(primes[i]) {
for(int j = 2 * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
Node[] verts = new Node[n];
for(int i = 0; i < n; i++) {
verts[i] = new Node(i, a[i]);
}
if(n % 2 == 1) {
System.out.println("Impossible");
return;
}
ArrayList<Integer> evens = new ArrayList<Integer>();
ArrayList<Integer> odds = new ArrayList<Integer>();
boolean[][] padj = new boolean[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(primes[a[i] + a[j]]) {
padj[i][j] = true;
padj[j][i] = true;
}
}
}
for(int i = 0; i < n; i++) {
if(verts[i].val % 2 == 0) {
evens.add(i);
} else {
odds.add(i);
}
}
int[][] adj = new int[n + 2][n + 2];
for(int i = 0; i < evens.size(); i++) {
adj[0][i + 1] = 2;
}
for(int i = 0; i < odds.size(); i++) {
adj[i + evens.size() + 1][n + 1] = 2;
}
for(int i = 0; i < evens.size(); i++) {
for(int j = 0; j < odds.size(); j++) {
if(padj[evens.get(i)][odds.get(j)]) {
adj[i + 1][j + evens.size() + 1] = 1;
}
}
}
int[][] copy = new int[n + 2][n + 2];
for(int i = 0; i < n + 2; i++) {
for(int j = 0; j < n + 2; j++) {
copy[i][j] = adj[i][j];
}
}
boolean works = true;
int tot = 0;
while(works) {
int curr = 0;
boolean[] hV = new boolean[n + 2];
Node2[] verts2 = new Node2[n + 2];
for(int i = 0; i < n + 2; i++) {
verts2[i] = new Node2(i);
}
verts2[0].ad.addLast(0);
verts2[0].cap = Integer.MAX_VALUE >> 1;
hV[0] = true;
boolean works2 = true;
while(curr != n + 1 && curr != -1) {
hV[curr] = true;
for(int i = 0; i < n + 2; i++) {
if(!hV[i] && verts2[i].cap < Math.min(verts2[curr].cap, adj[curr][i])) {
verts2[i].cap = Math.min(verts2[curr].cap, adj[curr][i]);
verts2[i].ad = new ArrayDeque<Integer>(verts2[curr].ad);
verts2[i].ad.addLast(i);
}
}
int ind = -1;
int max = 0;
for(int i = 0; i < n + 2; i++) {
if(!hV[i] && verts2[i].cap > max) {
max = verts2[i].cap;
ind = i;
}
}
curr = ind;
}
if(curr == -1) {
works = false;
} else {
tot += verts2[n + 1].cap;
ArrayDeque<Integer> ad = verts2[n + 1].ad;
int prev = ad.pollFirst();
while(!ad.isEmpty()) {
adj[prev][ad.peekFirst()] -= verts2[n + 1].cap;
adj[ad.peekFirst()][prev] += verts2[n + 1].cap;
prev = ad.pollFirst();
}
}
}
if(tot != n) {
System.out.println("Impossible");
} else {
boolean[][] newadj = new boolean[n][n];
for(int i = 0; i < evens.size(); i++) {
for(int j = 0; j < odds.size(); j++) {
if(copy[i + 1][j + evens.size() + 1] - adj[i + 1][j + evens.size() + 1] != 0 && i < j + evens.size()) {
newadj[evens.get(i)][odds.get(j)] = true;
}
}
}
Node3[] verts3 = new Node3[n];
for(int i = 0; i < n; i++) {
verts3[i] = new Node3(i);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(newadj[i][j]) {
verts3[i].adj.add(j);
verts3[j].adj.add(i);
}
}
}
int count = 0;
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
boolean[] hV = new boolean[n];
for(int i = 0; i < n; i++) {
if(!hV[i]) {
count++;
hV[i] = true;
ArrayList<Integer> templist = new ArrayList<Integer>();
templist.add(i);
int curr = i;
boolean works3 = true;
while(works3) {
int x = verts3[curr].adj.get(0);
int y = verts3[curr].adj.get(1);
if(!templist.contains(x)) {
templist.add(x);
curr = x;
hV[curr] = true;
} else {
if(!templist.contains(y)) {
templist.add(y);
curr = y;
hV[curr] = true;
} else {
works3 = false;
}
}
}
lists.add(templist);
}
}
System.out.println(count);
for(ArrayList<Integer> tmp : lists) {
System.out.print(tmp.size());
for(int foo : tmp) {
System.out.print(" " + (foo + 1));
}
System.out.println();
}
}
}
static class Node3 {
ArrayList<Integer> adj = new ArrayList<Integer>();
int id;
public Node3(int i) {
id = i;
}
}
static class Node2 {
int cap, id;
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
public Node2(int i) {
id = i;
cap = 0;
}
}
static class Node {
int val, id;
public Node(int i, int tempv) {
id = i;
val = tempv;
}
}
} | Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 0456c5c55b18e4370c314d8923b938a2 | train_002.jsonl | 1422894600 | Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws Exception {
new E().solve();
}
void solve() throws IOException {
FastScanner in = new FastScanner(System.in);
boolean[] isPrime = new boolean[112345];
Arrays.fill(isPrime, true);
for (int p = 2; p < isPrime.length; p++) {
if (isPrime[p]) {
for (int k = p + p; k < isPrime.length; k += p) {
isPrime[k] = false;
}
}
}
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int GN = n + 2;
int S = n;
int T = n + 1;
cap = new int[GN][GN];
nei = new LinkedList[GN];
for (int i = 0; i < nei.length; i++) {
nei[i] = new LinkedList<Integer>();
}
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
// S->
cnct(S, i, 2);
for (int jj = 0; jj < n; jj++) {
if (isPrime[a[i] + a[jj]]) {
cnct(i, jj, 1);
}
}
} else {
// ->T
cnct(i, T, 2);
}
}
int maxFlow = 0;
while (true) {
int f = flow(S, T, new boolean[GN], Integer.MAX_VALUE / 2, cap, nei);
maxFlow += f;
if (f == 0) {
break;
}
}
if (maxFlow != n) {
// ng!
System.out.println("Impossible");
return;
} else {
// ok
StringBuilder sb = new StringBuilder();
LinkedList<Integer> list = new LinkedList<Integer>();
boolean[] done = new boolean[n];
int cnt = 0;
for (int i = 0; i < n; i++) {
if (!done[i]) {
cnt++;
list.clear();
dfs(i, a[i] % 2 == 0, done, n, list);
sb.append(list.size());
for (int v : list) {
sb.append(" " + (v + 1));
}
sb.append("\n");
}
}
//
System.out.println(cnt);
System.out.print(sb);
}
}
void dfs(int idx, boolean even, boolean[] done, int n, List<Integer> list) {
done[idx] = true;
list.add(idx);
for (int ni = 0; ni < n; ni++) {
if (!done[ni] && (even ? cap[ni][idx] > 0 : cap[idx][ni] > 0)) {
dfs(ni, !even, done, n, list);
return;
}
}
}
int[][] cap;
LinkedList<Integer>[] nei;
void cnct(int a, int b, int v) {
cap[a][b] = v;
nei[a].add(b);
nei[b].add(a);
}
int flow(int idx, int T, boolean[] done, int lim, int[][] cap, List<Integer>[] nei) {
if (!done[idx]) {
if (idx == T) {
return lim;
} else {
done[idx] = true;
for (int ni : nei[idx]) {
if (cap[idx][ni] > 0) {
int f = flow(ni, T, done, Math.min(lim, cap[idx][ni]), cap, nei);
if (f > 0) {
// ok
cap[idx][ni] -= f;
cap[ni][idx] += f;
return f;
}
}
}
return 0;
}
} else {
return 0;
}
}
class FastScanner {
private InputStream _stream;
private byte[] _buf = new byte[1024];
private int _curChar;
private int _numChars;
private StringBuilder _sb = new StringBuilder();
FastScanner(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 next() {
int c = read();
while (isWhitespace(c)) {
c = read();
}
_sb.setLength(0);
do {
_sb.appendCodePoint(c);
c = read();
} while (!isWhitespace(c));
return _sb.toString();
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
public boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
| Java | ["4\n3 4 8 9", "5\n2 2 2 2 2", "12\n2 3 4 5 6 7 8 9 10 11 12 13", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"] | 2 seconds | ["1\n4 1 2 4 3", "Impossible", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4", "3\n6 1 2 3 6 5 4\n10 7 8 9 12 15 14 13 16 11 10\n8 17 18 23 22 19 20 21 24"] | NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | Java 7 | standard input | [
"flows"
] | 5a57929198fcc0836a5c308c807434cc | The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party. The second line contains n integers ai (2 ≤ ai ≤ 104). | 2,300 | If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. | standard output | |
PASSED | 9b7737678aa6548ce44baa3e9a70e882 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Banana {
public static boolean can(int []a,int n,int len)
{
int needed=0;
for(int x:a)
needed+=((x+n-1)/n);
if(len<needed)
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();int n=sc.nextInt();
int []count =new int[26];
for(char c:s.toCharArray())
count[c-'a']++;
int distinct=0;
for(int x:count)
if(x>0)
distinct++;
if(distinct>n)
{
System.out.println(-1);
return;
}
int lo=1;
int ans=0;
int hi=1000;
while(lo<=hi)
{
int mid=(lo+hi)/2;
if(can(count,mid,n))
{
ans=mid;
hi=mid-1;
}
else
lo=mid+1;
}
int left=n;
System.out.println(ans);
for(int j=0;j<26;j++)
{
int x=count[j];char c=(char)('a'+j);
int rep=(x+ans-1)/ans;
for(int i=0;i<rep;i++)
{
System.out.print(c);
left--;
}
}
while(left-->0)
System.out.print('a');
}
}
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();}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 85fcaeb3a6d55876aaed481a16ea7477 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Banana {
public static boolean can(int []a,int n,int len)
{
int needed=0;
for(int x:a)
{
if(x!=0)
needed+=((x+n-1)/n);
}
if(len<needed)
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();int n=sc.nextInt();
int []count =new int[26];
for(char c:s.toCharArray())
count[c-'a']++;
int distinct=0;
for(int x:count)
if(x>0)
distinct++;
if(distinct>n)
{
System.out.println(-1);
return;
}
int lo=1;
int ans=0;
int hi=1000;
while(lo<=hi)
{
int mid=(lo+hi)/2;
if(can(count,mid,n))
{
ans=mid;
hi=mid-1;
}
else
lo=mid+1;
}
int left=n;
System.out.println(ans);
for(int j=0;j<26;j++)
{
int x=count[j];char c=(char)('a'+j);
if(x!=0)
{
int rep=(x+ans-1)/ans;
for(int i=0;i<rep;i++)
{
System.out.print(c);
left--;
}
}
}
while(left-->0)
System.out.print('a');
}
}
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();}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 0fe70a3aff26c33e47e06cfea87d83a2 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void solve(InputReader in, OutputWriter out) {
String s = in.next();
int n = in.nextInt();
Map<Character, Integer> letters = new HashMap<>();
int maxCnt = 0;
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if (!letters.containsKey(letter))
letters.put(letter, 1);
else
letters.put(letter, letters.get(letter) + 1);
if (letters.get(letter) > maxCnt) maxCnt = letters.get(letter);
}
if (letters.size() > n)
out.print(-1);
else {
int l = 1, r = maxCnt;
while (l < r) {
int m = (l + r) / 2;
int tmp = n;
for (int cnt : letters.values()) {
int len = (int) Math.ceil(cnt * 1.0 / m);
tmp -= len;
if (tmp < 0) break;
}
if (tmp >= 0) {
r = m;
} else {
l = m + 1;
}
}
out.println(r);
int tmp = n;
char let = '!';
for (char letter : letters.keySet()) {
let = letter;
int len = (int) Math.ceil(letters.get(letter) * 1.0 / r);
tmp -= len;
for (int i = 0; i < len; i++) {
out.print(letter);
}
}
for (int i = 0; i < tmp; i++) {
out.print(let);
}
}
}
private static void shuffleArray(int[] array) {
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
solve(in, out);
in.close();
out.close();
}
private static class InputReader {
private BufferedReader br;
private StringTokenizer st;
InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String nextLine() {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String line = nextLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
byte nextByte() {
return Byte.parseByte(next());
}
short nextShort() {
return Short.parseShort(next());
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class OutputWriter {
BufferedWriter bw;
OutputWriter(OutputStream os) {
bw = new BufferedWriter(new OutputStreamWriter(os));
}
void print(int i) {
print(Integer.toString(i));
}
void println(int i) {
println(Integer.toString(i));
}
void print(long l) {
print(Long.toString(l));
}
void println(long l) {
println(Long.toString(l));
}
void print(double d) {
print(Double.toString(d));
}
void println(double d) {
println(Double.toString(d));
}
void print(boolean b) {
print(Boolean.toString(b));
}
void println(boolean b) {
println(Boolean.toString(b));
}
void print(char c) {
try {
bw.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(char c) {
println(Character.toString(c));
}
void print(String s) {
try {
bw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(String s) {
print(s);
print('\n');
}
void close() {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 49a577b105763eddb94f77415bdafa75 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.awt.Point;
public class Newbie {
static InputReader sc = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
solver s = new solver();
int t = 1;
while (t > 0) {
s.sol();
t--;
}
out.close();
}
/* static class descend implements Comparator<pair1> {
public int compare(pair1 o1, pair1 o2) {
if (o1.pop != o2.pop)
return (int) (o1.pop - o2.pop);
else
return o1.in - o2.in;
}
}*/
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream), 32768);
token = null;
}
public String sn() {
while (token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int ni() {
return Integer.parseInt(sn());
}
public String snl() throws IOException {
return br.readLine();
}
public long nlo() {
return Long.parseLong(sn());
}
public double nd() {
return Double.parseDouble(sn());
}
public int[] na(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.ni();
return a;
}
public long[] nal(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nlo();
return a;
}
}
static class ascend implements Comparator<pair> {
public int compare(pair o1, pair o2) {
return o2.b - o1.b;
}
}
static class extra {
static boolean v[] = new boolean[100001];
static List<Integer> l = new ArrayList<>();
static int t;
static void shuffle(int a[]) {
for (int i = 0; i < a.length; i++) {
int t = (int) Math.random() * a.length;
int x = a[t];
a[t] = a[i];
a[i] = x;
}
}
static void shufflel(long a[]) {
for (int i = 0; i < a.length; i++) {
int t = (int) Math.random() * a.length;
long x = a[t];
a[t] = a[i];
a[i] = x;
}
}
static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
static boolean valid(int i, int j, int r, int c) {
if (i >= 0 && i < r && j >= 0 && j < c) {
// System.out.println(i+" /// "+j);
return true;
} else {
// System.out.println(i+" //f "+j);
return false;
}
}
static void seive() {
for (int i = 2; i < 101; i++) {
if (!v[i]) {
t++;
l.add(i);
for (int j = 2 * i; j < 101; j += i)
v[j] = true;
}
}
}
static int binary(LinkedList<Integer> a, long val, int n) {
int mid = 0, l = 0, r = n - 1, ans = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (a.get(mid) == val) {
r = mid - 1;
ans = mid;
} else if (a.get(mid) > val)
r = mid - 1;
else {
l = mid + 1;
ans = l;
}
}
return (ans + 1);
}
static long fastexpo(long x, long y) {
long res = 1;
while (y > 0) {
if ((y & 1) == 1) {
res *= x;
}
y = y >> 1;
x = x * x;
}
return res;
}
static long lfastexpo(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) == 1) {
res = (res * x) % p;
}
y = y >> 1;
x = (x * x) % p;
}
return res;
}
/* void dijsktra(int s, List<pair> l[], int n) {
PriorityQueue<pair> pq = new PriorityQueue<>(new ascend());
int dist[] = new int[100005];
boolean v[] = new boolean[100005];
for (int i = 1; i <= n; i++)
dist[i] = 1000000000;
dist[s] = 0;
for (int i = 1; i < n; i++) {
if (i == s)
pq.add(new pair(s, 0));
else
pq.add(new pair(i, 1000000000));
}
while (!pq.isEmpty()) {
pair node = pq.remove();
v[node.a] = true;
for (int i = 0; i < l[node.a].size(); i++) {
int v1 = l[node.a].get(i).a;
int w = l[node.a].get(i).b;
if (v[v1])
continue;
if ((dist[node.a] + w) < dist[v1]) {
dist[v1] = dist[node.a] + w;
pq.add(new pair(v1, dist[v1]));
}
}
}
}*/
}
static class pair {
int a;
int b;
public pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static class pair1 {
pair p;
int in;
public pair1(pair a, int n) {
this.p = a;
this.in = n;
}
}
static int inf = 5000013;
static class solver {
DecimalFormat df = new DecimalFormat("0.00000000");
extra e = new extra();
long mod = (long) (1000000007);
void sol() throws IOException {
String s = sc.sn();
int n = s.length();
int k = sc.ni();
char c[] = s.toCharArray();
int inf[] = new int[26];
int add[] = new int[26];
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (inf[c[i] - 'a'] == 0) {
sb.append(c[i]);
cnt++;
}
inf[c[i] - 'a']++;
}
if (cnt > k) {
System.out.println(-1);
System.exit(0);
}
k -= cnt;
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> ((int) Math.ceil((inf[x] * 1.0) / add[x]) - (int) Math.ceil((inf[y] * 1.0) / add[y])) * -1);
for (int i = 0; i < 26; i++) {
if (inf[i] > 0) {
add[i]++;
pq.add(i);
}
}
while (k-- > 0 && !pq.isEmpty()) {
int t = pq.poll();
sb.append((char) (t + 'a'));
add[t]++;
pq.add(t);
}
int ans = -1;
for (int i = 0; i < 26; i++) {
if (inf[i] > 0)
ans = Math.max(ans, (int) Math.ceil((inf[i] * 1.0) / add[i]));
}
c = sb.toString().toCharArray();
Arrays.sort(c);
out.println(ans);
out.println(String.valueOf(c));
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | f15ff8f9e9256515c4b3c04cc703173c | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.awt.Point;
public class Newbie {
static InputReader sc = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
solver s = new solver();
int t = 1;
while (t > 0) {
s.sol();
t--;
}
out.close();
}
/* static class descend implements Comparator<pair1> {
public int compare(pair1 o1, pair1 o2) {
if (o1.pop != o2.pop)
return (int) (o1.pop - o2.pop);
else
return o1.in - o2.in;
}
}*/
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream), 32768);
token = null;
}
public String sn() {
while (token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int ni() {
return Integer.parseInt(sn());
}
public String snl() throws IOException {
return br.readLine();
}
public long nlo() {
return Long.parseLong(sn());
}
public double nd() {
return Double.parseDouble(sn());
}
public int[] na(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.ni();
return a;
}
public long[] nal(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nlo();
return a;
}
}
static class ascend implements Comparator<pair> {
public int compare(pair o1, pair o2) {
return o2.b - o1.b;
}
}
static class extra {
static boolean v[] = new boolean[100001];
static List<Integer> l = new ArrayList<>();
static int t;
static void shuffle(int a[]) {
for (int i = 0; i < a.length; i++) {
int t = (int) Math.random() * a.length;
int x = a[t];
a[t] = a[i];
a[i] = x;
}
}
static void shufflel(long a[]) {
for (int i = 0; i < a.length; i++) {
int t = (int) Math.random() * a.length;
long x = a[t];
a[t] = a[i];
a[i] = x;
}
}
static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
static boolean valid(int i, int j, int r, int c) {
if (i >= 0 && i < r && j >= 0 && j < c) {
// System.out.println(i+" /// "+j);
return true;
} else {
// System.out.println(i+" //f "+j);
return false;
}
}
static void seive() {
for (int i = 2; i < 101; i++) {
if (!v[i]) {
t++;
l.add(i);
for (int j = 2 * i; j < 101; j += i)
v[j] = true;
}
}
}
static int binary(LinkedList<Integer> a, long val, int n) {
int mid = 0, l = 0, r = n - 1, ans = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (a.get(mid) == val) {
r = mid - 1;
ans = mid;
} else if (a.get(mid) > val)
r = mid - 1;
else {
l = mid + 1;
ans = l;
}
}
return (ans + 1);
}
static long fastexpo(long x, long y) {
long res = 1;
while (y > 0) {
if ((y & 1) == 1) {
res *= x;
}
y = y >> 1;
x = x * x;
}
return res;
}
static long lfastexpo(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) == 1) {
res = (res * x) % p;
}
y = y >> 1;
x = (x * x) % p;
}
return res;
}
/* void dijsktra(int s, List<pair> l[], int n) {
PriorityQueue<pair> pq = new PriorityQueue<>(new ascend());
int dist[] = new int[100005];
boolean v[] = new boolean[100005];
for (int i = 1; i <= n; i++)
dist[i] = 1000000000;
dist[s] = 0;
for (int i = 1; i < n; i++) {
if (i == s)
pq.add(new pair(s, 0));
else
pq.add(new pair(i, 1000000000));
}
while (!pq.isEmpty()) {
pair node = pq.remove();
v[node.a] = true;
for (int i = 0; i < l[node.a].size(); i++) {
int v1 = l[node.a].get(i).a;
int w = l[node.a].get(i).b;
if (v[v1])
continue;
if ((dist[node.a] + w) < dist[v1]) {
dist[v1] = dist[node.a] + w;
pq.add(new pair(v1, dist[v1]));
}
}
}
}*/
}
static class pair {
int a;
int b;
public pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static class pair1 {
pair p;
int in;
public pair1(pair a, int n) {
this.p = a;
this.in = n;
}
}
static int inf = 5000013;
static class solver {
DecimalFormat df = new DecimalFormat("0.00000000");
extra e = new extra();
long mod = (long) (1000000007);
void sol() throws IOException {
String s = sc.sn();
int n = s.length();
int k = sc.ni();
char c[] = s.toCharArray();
int inf[] = new int[26];
int add[] = new int[26];
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (inf[c[i] - 'a'] == 0) {
sb.append(c[i]);
cnt++;
}
inf[c[i] - 'a']++;
}
if (cnt > k) {
System.out.println(-1);
System.exit(0);
}
k -= cnt;
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> ((int) Math.ceil((inf[x] * 1.0) / add[x]) - (int) Math.ceil((inf[y] * 1.0) / add[y])) * -1);
for (int i = 0; i < 26; i++) {
if (inf[i] > 0) {
add[i]++;
pq.add(i);
}
}
while (k-- > 0 && !pq.isEmpty()) {
int t = pq.poll();
sb.append((char) (t + 'a'));
add[t]++;
pq.add(t);
}
int ans = -1;
for (int i = 0; i < 26; i++) {
if (inf[i] > 0)
ans = Math.max(ans, (int) Math.ceil((inf[i] * 1.0) / add[i]));
}
out.println(ans);
out.println(sb);
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | e45aa9698b539690696856dc03f55c52 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
public class test {
static int getLen(HashMap<Character, Integer> map, int k){
int n = 0;
for (Map.Entry<Character, Integer> elem : map.entrySet()){
n += Math.ceil(((double) elem.getValue()) / k);
}
return n;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = sc.nextInt();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))){
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}
else {
map.put(s.charAt(i), 1);
}
}
if (n < map.size()){
System.out.println(-1);
}
else {
int left = 1;
int right = 1001;
int k = 1;
while (left < right) {
int mid = (left + right) / 2;
int len = getLen(map, mid);
if (len > n) {
left = mid + 1;
} else {
k = mid;
right = mid;
}
}
StringBuilder ans = new StringBuilder();
for (Map.Entry<Character, Integer> elem : map.entrySet()){
int size =(int) Math.ceil(((double) elem.getValue()) / k);
for (int i = 0; i < size; i++) {
ans.append(elem.getKey());
}
}
while (ans.length() < n){
ans.append(s.charAt(0));
}
System.out.println(k);
System.out.println(ans);
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 76c484cfbf95d282c39611e9c90debdc | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
public class test {
static int getLen(HashMap<Character, Integer> map, int k){
int n = 0;
for (Map.Entry<Character, Integer> elem : map.entrySet()){
n += Math.ceil(((double) elem.getValue()) / k);
}
return n;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = sc.nextInt();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))){
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}
else {
map.put(s.charAt(i), 1);
}
}
if (n < map.size()){
System.out.println(-1);
}
else {
int left = 1;
int right = 1000;
int k = 1;
for (int i = 1; i <= 1000; i++) {
if (getLen(map, i) <= n){
k = i;
break;
}
}
StringBuilder ans = new StringBuilder();
for (Map.Entry<Character, Integer> elem : map.entrySet()){
int size =(int) Math.ceil(((double) elem.getValue()) / k);
for (int i = 0; i < size; i++) {
ans.append(elem.getKey());
}
}
while (ans.length() < n){
ans.append(s.charAt(0));
}
System.out.println(k);
System.out.println(ans);
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | b8fd1e6b1b0fd7b22657785ef0a574ab | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
class GraphBuilder {
int n, m;
int[] x, y;
int index;
int[] size;
GraphBuilder(int n, int m) {
this.n = n;
this.m = m;
x = new int[m];
y = new int[m];
size = new int[n];
}
void add(int u, int v) {
x[index] = u;
y[index] = v;
size[u]++;
size[v]++;
index++;
}
int[][] build() {
int[][] graph = new int[n][];
for (int i = 0; i < n; i++) {
graph[i] = new int[size[i]];
}
for (int i = index - 1; i >= 0; i--) {
int u = x[i];
int v = y[i];
graph[u][--size[u]] = v;
graph[v][--size[v]] = u;
}
return graph;
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long[] readLongArray(int size) throws IOException {
long[] res = new long[size];
for (int i = 0; i < size; i++) {
res[i] = readLong();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Template().run();
// new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
void solve() throws IOException {
char[] s = readString().toCharArray();
int n = readInt();
TreeSet<Character> uniq = new TreeSet<>();
for (char x : s) {
uniq.add(x);
}
if (uniq.size() > n) {
out.println(-1);
return;
}
int[] cnt = new int[26];
for (char x : s) {
cnt[x - 'a']++;
}
int l = 1;
int r = 100000;
int pages = 0;
while (l <= r) {
int mid = (l + r) >> 1;
int need = 0;
for (int i = 0; i < 26; i++) {
need += (cnt[i] + mid - 1) / mid;
}
if (need <= n) {
pages = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
out.println(pages);
for (int i = 0; i < 26; i++) {
int c = (cnt[i] + pages - 1) / pages;
while (c-- > 0) {
out.print((char) ('a' + i));
n--;
}
}
while (n-- > 0) {
out.print("a");
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 183b2bedbb33c171678c1a2285969770 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CF335A {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
char s[] = sc.next().toCharArray();
int n = sc.nextInt();
int f[] = new int[26];
boolean found = false;
for (int i = 0; i < s.length; i++)
f[s[i] - 'a']++;
for (int k = 1; k <= s.length; k++) {
int ans = sum(f, k);
if (ans <= n) {
found = true;
System.out.println(k);
int len = 0;
for (int i = 0; i < 26; i++) {
int rep = (int) Math.ceil(f[i] * 1.0 / k);
while (rep-- > 0) {
System.out.print((char) (i + 'a'));
len++;
}
}
while (len < n) {
System.out.print('a');
len++;
}
break;
}
}
System.out.println(!found ? -1 : "");
}
static int sum(int f[], int k) {
int ans = 0;
for (int i = 0; i < f.length; i++) {
ans += (int) Math.ceil(f[i] * 1.0 / k);
}
return ans;
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 36b1bb6d39257e44d0a5024ee5d3c061 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 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;
public class C {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
char[] a = sc.next().toCharArray();
int n = sc.nextInt();
int[] occ1 = new int[27];
for(char c : a)
occ1[c-'a']++;
int res = -1;
int occ2[] = null, c = 0;
for(int sheets = 1; sheets <= 1000; sheets++)
{
occ2 = new int[27];
c = 0;
for(int i = 0; i < 27; i++)
if(occ1[i] > 0)
{
occ2[i] = occ1[i] / sheets;
if(occ1[i] % sheets != 0) occ2[i]++;
c += occ2[i];
}
if(c <= n)
{
res = sheets;
break;
}
}
while(c++ < n) occ2[0]++;
out.println(res);
if(res != -1)
{
for(int i = 0; i < 27; i++)
while(occ2[i]-- > 0)
out.print((char) (i + 'a'));
out.println();
}
out.flush();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput(){for(long i = 0; i < 3e9; i++);}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 4fbefe9bc18adca3510344ce3f9b9cb9 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out){
String s = in.next();
int n = in.ri();
int[] count = new int[26];
for(char c : s.toCharArray()) count[c-'a']++;
int min = 1, max = 1003;
while(min < max){
int middle = (min + max) / 2;
if(works(middle, count, n)) max = middle;
else min = middle + 1;
}
for(int i = 0; i < 26; i++) count[i] = IntegerUtils.roundUp(count[i], min);
StringBuilder res = new StringBuilder();
for(int i = 0; i < 26; i++) while(count[i] > 0) {res.append((char) (i+'a')); count[i]--;}
while(res.length() < n) res.append('a');
if (min == 1003) {out.printLine(-1); return;}
out.printLine(min);
out.printLine(res.toString());
}
private boolean works(int middle, int[] count, int n){
int length = 0;
for(int i = 0; i < 26; i++) length += IntegerUtils.roundUp(count[i], middle);
return length <= n;
}
}
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 ri(){
return readInt();
}
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 {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
class IntegerUtils {
public static int roundUp(int a, int b) {
assert(b > 0);
int d = a % b;
if (d < 0) d += b;
if (d != 0) a += b - d;
return a / b;
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | f7f6de873b6c1111ce01a0082a8b01be | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static long gcd(long a, long b){ return (b==0) ? a : gcd(b, a%b); }
static int gcd(int a, int b){ return (b==0) ? a : gcd(b, a%b); }
private static int fact(int n) { int ans=1; for(int i=2;i<=n;i++) ans*=i; return ans; }
public static int[] generatePrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, 2, n + 1, true);
for (int i = 2; i * i <= n; i++)
if (prime[i])
for (int j = i * i; j <= n; j += i)
prime[j] = false;
int[] primes = new int[n + 1];
int cnt = 0;
for (int i = 0; i < prime.length; i++)
if (prime[i])
primes[cnt++] = i;
return Arrays.copyOf(primes, cnt);
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next(){while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/********* SOLUTION STARTS HERE ************/
private static void solve(FastScanner in, PrintWriter out){
String s = in.next();
int len = in.nextInt();
int n = s.length();
int l=1,r=n+1;
int a[] = new int[26];
for(int i=0;i<n;i++) a[s.charAt(i)-'a']++;
int cnt=0;
for(int i:a) if(i!=0) cnt++;
if(cnt > len) {out.println(-1);return;}
while(l<r){
int mid = (l+r)>>1;
int need=0;
for(int i=0;i<26;i++){
need += (a[i]+mid-1)/mid;
}
if(need <= len) r = mid;
else l = mid+1;
}
out.println(l);cnt=0;
for(int i=0;i<26;i++){
int tmp = (a[i]+l-1)/l;
for(int j=0;j<tmp;j++) {out.print((char)(i+'a'));cnt++;}
}
while(cnt<len) {out.print("a");cnt++;}
out.println();
}
/************* SOLUTION ENDS HERE **********/
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 8f403b0d74f3e08d23a366bf523228ce | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
public class CF335A {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
char []input = sc.nextLine().toCharArray();
int n = Integer.parseInt(sc.nextLine());
int []inputCharFreq = new int[26];
int uniqueChars = 0;
for (int i = 0; i < input.length; i++) {
int index = input[i] - 'a';
if (inputCharFreq[index] == 0) uniqueChars++;
inputCharFreq[index]++;
}
if (n < uniqueChars) {
System.out.println(-1);
return;
}
char []output = new char[n];
int []outputCharFreq = new int[26];
int i = 0, j = 0;
for (; i < uniqueChars; i++) {
while (inputCharFreq[j] == 0) j++;
output[i] = (char) (j + 'a');
outputCharFreq[j++]++;
}
if (n >= input.length) {
// Fill remaining characters
j = 0;
for (; i < input.length; i++) {
while (j < 26 && inputCharFreq[j] - outputCharFreq[j] <= 0) j++;
if (j >= 26) break;
output[i] = (char) (j + 'a');
outputCharFreq[j]++;
}
// Fill in dummy characters
for (; i < n; i++) {
output[i] = 'a';
outputCharFreq[0]++;
}
} else {
for (; i < n; i++) {
double maximumRatio = 0.0;
int maxRatioIndex = 0;
for (j = 0; j < uniqueChars; j++) {
int index = output[j] - 'a';
if (outputCharFreq[index] == 0) continue;
double ratio = inputCharFreq[index] / (double) outputCharFreq[index];
if (ratio > maximumRatio) {
maximumRatio = ratio;
maxRatioIndex = index;
}
}
output[i] = (char) (maxRatioIndex + 'a');
outputCharFreq[maxRatioIndex]++;
}
}
double maxRatio = 0;
for (i = 0; i < uniqueChars; i++) {
int index = output[i] - 'a';
double ratio = inputCharFreq[index] / (double) outputCharFreq[index];
maxRatio = Math.max(ratio, maxRatio);
}
System.out.println((int) Math.ceil(maxRatio));
System.out.println(output);
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 375e938c0a8ce3b02ca52291fdd6e209 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
public class Main implements Runnable {
int INF = (int) 1e9;
List<Integer> edges[];
int anc[][];
int ts[], te[];
int t;
private void solve() throws IOException {
String s = next();
int n = nextInt();
int cnt[] = new int[26];
int dist = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (cnt[ch - 'a'] == 0) {
dist++;
}
cnt[ch - 'a']++;
}
if (n < dist) {
pw.println(-1);
return;
}
int l = 0;
int r = s.length();
while (r - l > 1) {
int mid = (l + r) >> 1;
int tot = 0;
for (int i = 0; i < 26; ++i) {
tot += ((cnt[i] + mid - 1) / mid);
}
if (tot > n) {
l = mid;
} else {
r = mid;
}
}
pw.println(r);
int need = 0;
for (int i = 0; i < 26; ++i) {
need += (cnt[i] + r - 1) / r;
for (int j = 0; j < (cnt[i] + r - 1) / r; ++j) {
pw.print((char) ('a' + i));
}
}
while (need < n) {
pw.print('x');
need++;
}
}
BufferedReader br;
StringTokenizer st;
PrintWriter pw;
public static void main(String args[]) {
new Main().run();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
st = null;
solve();
pw.flush();
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 193ec2152bc0b52b5c6fa287d22e4dc8 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
public class Main implements Runnable {
int INF = (int) 1e9;
List<Integer> edges[];
int anc[][];
int ts[], te[];
int t;
private void solve() throws IOException {
String s = next();
int n = nextInt();
int cnt[] = new int[26];
int dist = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (cnt[ch - 'a'] == 0) {
dist++;
}
cnt[ch - 'a']++;
}
if (n < dist) {
pw.println(-1);
return;
}
int l = 0;
int r = s.length();
while (r - l > 1) {
int mid = (l + r) >> 1;
int tot = 0;
for (int i = 0; i < 26; ++i) {
tot += ((cnt[i] + mid - 1) / mid);
}
if (tot > n) {
l = mid;
} else {
r = mid;
}
}
pw.println(r);
int need = 0;
for (int i = 0; i < 26; ++i) {
need += (cnt[i] + r - 1) / r;
for (int j = 0; j < (cnt[i] + r - 1) / r; ++j) {
pw.print((char) ('a' + i));
}
}
while (need < n) {
pw.print("x");
need++;
}
}
BufferedReader br;
StringTokenizer st;
PrintWriter pw;
public static void main(String args[]) {
new Main().run();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
st = null;
solve();
pw.flush();
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | beb9e5f2b2996433057adb4db5c0b64d | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
public class Main implements Runnable {
int INF = (int) 1e9;
List<Integer> edges[];
int anc[][];
int ts[], te[];
int t;
private void solve() throws IOException {
String s = next();
int n = nextInt();
int cnt[] = new int[26];
int dist = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (cnt[ch - 'a'] == 0) {
dist++;
}
cnt[ch - 'a']++;
}
if (n < dist) {
pw.println(-1);
return;
}
int l = 0;
int r = s.length();
while (r - l > 1) {
int mid = (l + r) >> 1;
int tot = 0;
for (int i = 0; i < 26; ++i) {
tot += ((cnt[i] + mid - 1) / mid);
}
if (tot > n) {
l = mid;
} else {
r = mid;
}
}
pw.println(r);
int need = 0;
for (int i = 0; i < 26; ++i) {
need += (cnt[i] + r - 1) / r;
for (int j = 0; j < (cnt[i] + r - 1) / r; ++j) {
pw.print((char) ('a' + i));
}
}
while (need < n) {
pw.printf("x");
need++;
}
}
BufferedReader br;
StringTokenizer st;
PrintWriter pw;
public static void main(String args[]) {
new Main().run();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
st = null;
solve();
pw.flush();
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 2f8ad6c2c3e5592ea359ab31b17eb889 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Banana implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
char[] x = in.next().toCharArray();
int n = in.ni(), unique = 0;
int[] cnt = new int[26];
for (char c : x) {
cnt[c - 'a']++;
if (cnt[c - 'a'] == 1) unique++;
}
if (unique > n) {
out.println(-1);
return;
}
int lo = 1, hi = 1005, min = 1005;
while (lo <= hi) {
int mid = (lo + hi) / 2;
int total = 0;
for (int i = 0; i < 26; i++) {
if (cnt[i] > 0) {
if (cnt[i] <= mid) total++;
else {
total += (cnt[i] / mid) + (cnt[i] % mid != 0 ? 1 : 0);
}
}
}
if (total <= n) {
min = Math.min(min, mid);
hi = mid - 1;
} else {
lo = mid + 1;
}
}
char[] result = new char[n];
int idx = 0;
for (int i = 0; i < 26; i++) {
if (cnt[i] > 0) {
if (cnt[i] <= min) result[idx++] = (char) ('a' + i);
else {
int times = (cnt[i] / min) + (cnt[i] % min != 0 ? 1 : 0);
for (int j = 0; j < times; j++) {
result[idx++] = (char) ('a' + i);
}
}
}
}
while (idx < n) {
result[idx++] = 'a';
}
out.println(min);
for (int i = 0; i < result.length; i++) {
out.print(result[i]);
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (Banana instance = new Banana()) {
instance.solve();
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | cf7f8337c0e897292e3ebba25c985d03 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws Throwable
{
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader br = new BufferedReader(new FileReader("out1"));
// PrintWriter out = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileReader("out1"));
String s = sc.nextLine();
char[] arr = s.toCharArray();
int n = sc.nextInt();
if(n>=arr.length)
{
System.out.println(1);
StringBuilder sb = new StringBuilder(s);
n -= s.length();
while(n-->0)
{
sb.append(s.charAt(0));
}
System.out.println(sb);
return;
}
int[] count = new int[26];
int total = 0;
for (int i = 0; i < arr.length; i++) {
if(count[arr[i]-'a']==0)
total++;
count[ arr[i]-'a' ]++;
}
if(total>n)
{
System.out.println(-1);
return;
}
int[] res = new int[26];
for (int i = 0; i < count.length; i++) {
if(count[i]>0)
{
n--;
res[i]++;
count[i]--;
}
}
while(n>0)
{
int max = 0;
int ind = 0;
for (int i = 0; i < count.length && n>0; i++)
{
if(count[i]>0)
{
int cur = (int) Math.ceil((1.0*count[i])/res[i]);
if(cur>max)
{
max = cur;
ind = i;
}
}
}
res[ind]++;
count[ind]--;
n--;
}
int ans = 0;
count = new int[26];
for(int i = 0;i<s.length();i++)
{
count[ arr[i]-'a' ]++;
}
for (int i = 0; i < count.length; i++) {
ans = Math.max(ans, (int)Math.ceil((1.0*count[i])/res[i]));
}
System.out.println(ans);
for (int i = 0; i < res.length; i++) {
while(res[i]-->0)
{
System.out.print((char)(i+'a'));
}
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
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();}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 49a5861075c30d413643481c51ffff95 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.Scanner;
public class Banana {
static String sol;
static int n;
private static int [] freq = new int[26];
public static void main(String[] args)
{
Scanner fin = new Scanner(System.in);
String s = fin.nextLine();
n = fin.nextInt();
int i;
for (i = 0; i < s.length(); i++) {
freq[s.charAt(i) - 'a'] ++;
}
int cnt = 0;
for (i = 0; i < 26; i++)
if (freq[i] != 0)
cnt ++;
if (cnt > n) {
System.out.println(-1);
return;
}
int p = 0;
int st = 1 ;
int dr = 1000;
while (st <= dr) {
int mid = (st + dr) >> 1;
if (solve(mid) <= n) {
p = mid;
dr = mid - 1;
}
else
st = mid + 1;
}
System.out.println(p);
sol = "";
for (i = 0; i < 26; i++) {
int now_need = now_need = (freq[i] + p - 1) / p;
while (now_need > 0) {
sol = sol +(char)(i + 'a');
now_need --;
}
}
if (sol.length() > n) {
System.out.println(-1);
return;
}
while (sol.length() != n)
sol += 'a';
System.out.println(sol);
}
private static int solve(int p) {
int i, need = 0, now_need;
for (i = 0; i < 26; i++) {
now_need = (freq[i] + p - 1) / p;
need += now_need;
}
return need;
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | a78e9ef75ce6dd81200e271c297903be | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.function.*;
public class Main {
final static String fileName = "";
final static boolean useFiles = false;
public static void main(String[] args) throws FileNotFoundException {
InputStream inputStream;
OutputStream outputStream;
if (useFiles) {
inputStream = new FileInputStream(fileName + ".in");
outputStream = new FileOutputStream(fileName + ".out");
} else {
inputStream = System.in;
outputStream = System.out;
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task(in, out);
Debug.out = out;
solver.solve();
out.close();
}
}
class Task {
public void solve() {
String s = in.next();
int[] sc = ArrayUtils.countingSort(s);
int n = in.nextInt();
for (int ans = 1; ans <= s.length(); ans++) {
int sum = 0;
for (int j = 0; j < 26; j++) {
sum += MathUtils.ceilDiv(sc[j], ans);
}
if (sum <= n) {
out.println(ans);
String result = "";
for (char c = 'a'; c <= 'z'; c++) {
for (int j = 0; j < MathUtils.ceilDiv(sc[c - 'a'], ans); j++)
result += c;
}
int cnt = n - result.length();
for (int i = 0; i < cnt; i++)
result += 'a';
out.print(result);
return;
}
}
out.print(-1);
}
private InputReader in;
private PrintWriter out;
Task(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
}
class Debug {
public static PrintWriter out;
public static void printObjects(Object... objects) {
out.println(Arrays.deepToString(objects));
out.flush();
}
}
class ArrayUtils {
static int[] countingSort(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
return count;
}
static int[] scaling(int[] a) {
int[] types = unique(a);
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++)
result[i] = Arrays.binarySearch(types, a[i]);
return result;
}
static int[] filter(int[] array, Predicate<Integer> predicate) {
int count = 0;
for (int anArray : array) {
if (predicate.test(anArray))
count++;
}
int[] result = new int[count];
int top = 0;
for (int anArray : array) {
if (predicate.test(anArray))
result[top++] = anArray;
}
return result;
}
static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
for (; i < a.length && j < b.length; k++) {
if (a[i] < b[i])
result[k] = a[i++];
else
result[k] = b[j++];
}
for (; i < a.length; i++)
result[k++] = a[i];
for (; j < b.length; j++)
result[k++] = a[j];
return result;
}
static int[] reverse(int[] a) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++)
result[i] = a[a.length - i - 1];
return result;
}
static int[] unique(int[] a) {
a = a.clone();
Arrays.sort(a);
int n = a.length;
int count = 1;
for (int i = 1; i < n; i++) {
if (a[i] != a[i - 1])
count++;
}
int[] result = new int[count];
result[0] = a[0];
for (int i = 1, j = 1; i < n; i++) {
if (a[i] != a[i - 1])
result[j++] = a[i];
}
return result;
}
}
class Combinatorics {
private int[] f;
private int size;
private int mod;
Combinatorics(int n, int mod) {
f = new int[n];
f[0] = 1;
for (int i = 1; i <= n; i++)
f[i] = (int) ((f[i - 1] * ((long) i)) % mod);
size = n;
}
int combinations(int n, int k) {
if (k > n || k > size || n > size)
throw new IllegalArgumentException();
long result = f[n];
result *= MathUtils.inverse(k, mod);
result %= mod;
result *= MathUtils.inverse(n - k, mod);
return (int) (result % mod);
}
int factorial(int x) {
if (x > size)
throw new IllegalArgumentException();
return f[x];
}
int arrangements(int n, int k) {
if (n > size || k > size || k > n)
throw new IllegalArgumentException();
return (int) ((f[n] * ((long) MathUtils.inverse(f[n - k], mod))) % mod);
}
int b(int n, int k) {
return combinations(n + k - 1, n - 1);
}
}
class Tuple<T1, T2> {
Tuple(T1 first, T2 second) {
First = first;
Second = second;
}
T1 First;
T2 Second;
}
class Tuple3<T1, T2, T3> {
Tuple3(T1 first, T2 second, T3 third) {
First = first;
Second = second;
Third = third;
}
T1 First;
T2 Second;
T3 Third;
}
class MathUtils {
static int ceilDiv(int a, int b) {
return (a + b - 1) / b;
}
static boolean isPrime(int x) {
for (long i = 2; i * i <= x; i++) {
if (x % i == 0)
return false;
}
return true;
}
static int getNextPrime(int x) {
for (int i = x; ; i++) {
if (isPrime(i))
return i;
}
}
static boolean[] eratosphen(int n) {
boolean[] result = new boolean[n + 1];
for (int i = 2; sqr((long) i) <= n; i++) {
if (!result[i]) {
for (int j = i * i; j <= n; j += i)
result[j] = true;
}
}
return result;
}
static List<Tuple<Integer, Integer>> factorize(int x) {
List<Tuple<Integer, Integer>> result = new ArrayList<Tuple<Integer, Integer>>();
for (long div = 2; div * div <= x; div++) {
if (x % div == 0) {
int count = 0;
do {
count++;
x /= div;
}
while (x % div == 0);
result.add(new Tuple<Integer, Integer>((int) div, count));
}
}
if (x != 1) {
result.add(new Tuple<Integer, Integer>(x, 1));
}
return result;
}
static long lcm(int a, int b) {
return ((long) a) * b / gcd(a, b);
}
static int gcd(int a, int b) {
if (a <= 0 || b <= 0)
throw new IllegalArgumentException("Not positive arguments: " + a + " and " + b);
return privateGcd(Math.min(a, b), Math.max(a, b));
}
private static int privateGcd(int a, int b) {
if (a == 0)
return b;
return privateGcd(b % a, a);
}
static double sqr(double a) {
return a * a;
}
static long sqr(long a) {
return a * a;
}
static int sqr(int a) {
return a * a;
}
static int power(int base, int pow, int mod) {
long s = base;
long result = 1;
while (pow != 0) {
if ((pow & 1) > 0) {
result *= s;
result %= mod;
}
s = sqr(s) % mod;
pow >>= 1;
}
return (int) result;
}
static int inverse(int x, int mod) {
return power(x, mod - 2, mod);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public double nextDouble(){
return Double.parseDouble(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 2fd3e50003e5534183a8128dd4c79c6d | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.io.BufferedReader;
public class Main{
static int[][] grid;
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int[] alphabet = new int[26];
String s = sc.next();
int limit = sc.nextInt();
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
alphabet[s.charAt(i)-'a']++;
if (alphabet[s.charAt(i)-'a'] == 1) {
ans.append(s.charAt(i));
limit--;
}
}
HashMap<Character, Integer> freq = new HashMap<Character, Integer>();
PriorityQueue<pair> max = new PriorityQueue<pair>();
for (int i = 0; i < 26; i++) {
if (alphabet[i] > 1) {
max.add(new pair((char) (i+'a'), alphabet[i]));
freq.put((char) (i+'a'),1);
}
}
while (limit > 0 && !max.isEmpty()) {
pair cur = max.poll();
ans.append(cur.c);
freq.put(cur.c,freq.get(cur.c) +1);
cur.freq = (alphabet[cur.c-'a']/freq.get(cur.c) + ((alphabet[cur.c-'a']%freq.get(cur.c)) != 0?1:0));
if (cur.freq > 1) {
max.add(cur);
}
limit--;
}
if (limit < 0) {
out.println(-1);
}
else {
while (limit > 0) {
ans.append(s.charAt(0));
limit--;
}
if (max.isEmpty()) {
out.println(1);
}
else {
out.println(max.poll().freq);
}
out.println(ans.toString());
}
out.flush();
}
static class pair implements Comparable<pair>{
char c;
int freq;
pair(char c,int freq){
this.c = c;
this.freq = freq;
}
public int compareTo(pair o) {
return o.freq - this.freq;
}
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | abcefd0f7d86904227b25279ebc61834 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Main {
public 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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static final int MAX = 100005;
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
int n;
String s;
TreeMap<Character,Integer> m = new TreeMap<Character,Integer>();
s = sc.next();
n = sc.nextInt();
for (int i = 0; i < s.length(); i++) {
if(m.get(s.charAt(i))== null){
m.put(s.charAt(i), 1);
}
else{
m.put(s.charAt(i), m.get(s.charAt(i))+1);
}
}
if (m.size() > n) {
System.out.print(-1);
return;
}
int l = 1, r = s.length();
while (l < r) {
int mid = (l + r) / 2, cnt = 0;
for (Map.Entry<Character, Integer> it : m.entrySet()) {
cnt += Math.ceil(1.0 * it.getValue() / mid);
}
if (cnt <= n) {
r = mid;
}
else {
l = mid + 1;
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<Character, Integer> it : m.entrySet()) {
for (int i = 0; i < Math.ceil(1.0 * it.getValue() / r); i++) {
sb.append(it.getKey());
}
}
while (sb.length() < n) {
sb.append('a');
}
System.out.println(r);
System.out.println(sb);
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | edbd7bac3718a8eda536e66c4a34c74e | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
import javax.sound.midi.Synthesizer;
public class Problem5 {
static ArrayList<Integer> primes;
static void sieve(int N)
{
boolean[] isComposite = new boolean[N];
primes = new ArrayList<Integer>(N / 10);
for(int i = 2; i < N; ++i)
if(!isComposite[i])
{
primes.add(i);
if(1l * i * i < N)
for(int j = i * i; j < N; j += i)
isComposite[j] = true;
}
}
/* static ArrayList<Pair> primeFactors(int N)
*{
ArrayList<Pair> factors = new ArrayList<Pair>();
int idx = 0, p = primes.get(0);
while(1l * p * p <= N)
{
int e = 0;
while(N % p == 0)
{
N /= p;
++e;
}
if(e != 0)
factors.add(new Pair(p, e));
p = primes.get(++idx);
}
if(N != 1)
factors.add(new Pair(N, 1));
return factors;
}**/
static double eps= 1e-12;
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s=sc.nextLine();
int n=sc.nextInt();
HashSet<Character> set=new HashSet<>();
char c[]=s.toCharArray();
StringBuilder sb=new StringBuilder();
int d[]=new int[26];
int count[]=new int[26];
PriorityQueue<Pair> pq=new PriorityQueue<Pair>();
TreeMap<Character,Integer> map=new TreeMap<>();
for (int i = 0; i < c.length; i++) {
count[c[i]-'a']++;
}
for (int i = 0; i < c.length; i++) {
if(!set.contains(c[i])) {
set.add(c[i]);
sb.append(c[i]);
d[c[i]-'a']++;
}
}
if(set.size()>n) {
System.out.println(-1);
return;
}
n=n-set.size();
char c1='a';
for (int i = 0; i < count.length; i++) {
if(count[c1-'a']>0)
pq.add(new Pair(c1,count[c1-'a']));
c1++;
}
while(!pq.isEmpty()&&n>0) {
Pair p=pq.remove();
sb.append(p.p);
d[p.p-'a']++;
pq.add(new Pair(p.p,(int) Math.ceil(1.0*count[p.p-'a']/d[p.p-'a']*1.0)));
n--;
}
while(n>0) {
sb.append('a');
d[0]++;
n--;
}
int max=1;
for (int i = 0; i < d.length; i++) {
for (int j = 2; j <=1000; j++) {
if(d[i]>=count[i]) {
break;
}
else if(d[i]*j>=count[i]) {
max=Math.max(j, max);
break;
}
}
}
System.out.println(max);
System.out.println(sb);
/**for(Map.Entry<Character,Integer> entry : map.entrySet()) {
char key = entry.getKey();
Integer value = entry.getValue();
}**/
out.flush();
}
static class Pair implements Comparable<Pair>
{
char p;int e;
Pair(char x, int y) { p = x; e = y; }
@Override
public int compareTo(Pair o) {
if(this.e<o.e)
return 1;
else
return -1;
}
}
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 = br.readLine();
st = new StringTokenizer(s);
return s.isEmpty();
}
public void waitForInput() throws InterruptedException {Thread.sleep(2500);}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 71281d0a7045822cdfb774444b7256d2 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
import javax.sound.midi.Synthesizer;
public class Problem5 {
static ArrayList<Integer> primes;
static void sieve(int N)
{
boolean[] isComposite = new boolean[N];
primes = new ArrayList<Integer>(N / 10);
for(int i = 2; i < N; ++i)
if(!isComposite[i])
{
primes.add(i);
if(1l * i * i < N)
for(int j = i * i; j < N; j += i)
isComposite[j] = true;
}
}
/* static ArrayList<Pair> primeFactors(int N)
*{
ArrayList<Pair> factors = new ArrayList<Pair>();
int idx = 0, p = primes.get(0);
while(1l * p * p <= N)
{
int e = 0;
while(N % p == 0)
{
N /= p;
++e;
}
if(e != 0)
factors.add(new Pair(p, e));
p = primes.get(++idx);
}
if(N != 1)
factors.add(new Pair(N, 1));
return factors;
}**/
static double eps= 1e-12;
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s=sc.nextLine();
int n=sc.nextInt();
HashSet<Character> set=new HashSet<>();
char c[]=s.toCharArray();
StringBuilder sb=new StringBuilder();
int d[]=new int[26];
int count[]=new int[26];
PriorityQueue<Pair> pq=new PriorityQueue<Pair>();
TreeMap<Character,Integer> map=new TreeMap<>();
for (int i = 0; i < c.length; i++) {
count[c[i]-'a']++;
}
for (int i = 0; i < c.length; i++) {
if(!set.contains(c[i])) {
set.add(c[i]);
sb.append(c[i]);
d[c[i]-'a']++;
}
}
if(set.size()>n) {
System.out.println(-1);
return;
}
n=n-set.size();
char c1='a';
for (int i = 0; i < count.length; i++) {
if(count[c1-'a']>0)
pq.add(new Pair(c1,count[c1-'a']));
c1++;
}
while(!pq.isEmpty()&&n>0) {
Pair p=pq.remove();
sb.append(p.p);
d[p.p-'a']++;
pq.add(new Pair(p.p,(int) Math.ceil(1.0*count[p.p-'a']/d[p.p-'a']*1.0)));
n--;
}
while(n>0) {
sb.append('a');
d[0]++;
n--;
}
int max=1;
for (int i = 0; i < d.length; i++) {
for (int j = 2; j <=1000; j++) {
if(d[i]>=count[i]) {
break;
}
else if(d[i]*j>=count[i]) {
max=Math.max(j, max);
break;
}
}
}
System.out.println(max);
System.out.println(sb);
/**for(Map.Entry<Character,Integer> entry : map.entrySet()) {
char key = entry.getKey();
Integer value = entry.getValue();
}**/
out.flush();
}
static class Pair implements Comparable<Pair>
{
char p;int e;
Pair(char x, int y) { p = x; e = y; }
@Override
public int compareTo(Pair o) {
if(this.e<o.e)
return 1;
else
return -1;
}
}
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 = br.readLine();
st = new StringTokenizer(s);
return s.isEmpty();
}
public void waitForInput() throws InterruptedException {Thread.sleep(2500);}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 7b2717cefc3e91e8563caaf8ab01a3d1 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Banana {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = Integer.parseInt(br.readLine());
int[] countOcc = new int[26];
int distinctCount = 0;
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i) - 'a';
if (countOcc[c] == 0)
distinctCount++;
countOcc[c]++;
}
if (distinctCount > n) {
System.out.println(-1);
return;
}
int sheetsCount = 1;
while (true) {
int lettersCount = 0;
for (int i = 0; i < 26; i++) {
lettersCount += Math.ceil((countOcc[i] * 1.0) / (sheetsCount * 1.0));
}
if (lettersCount <= n) {
System.out.println(sheetsCount);
for (int i = 0; i < 26; i++) {
int occ = (int) Math.ceil((countOcc[i] * 1.0) / (sheetsCount * 1.0));
char c = (char) (i + 'a');
for (int j = 0; j < occ; j++)
System.out.print(c);
}
for (int i = lettersCount; i < n; i++) {
System.out.print('a');
}
break;
}
sheetsCount ++;
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 90821ea76c1684990ac640a7ecb4a237 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Abood3A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = sc.next();
int n = sc.nextInt();
int[] c = new int[26];
for (int i = 0; i < s.length(); i++) {
c[s.charAt(i) - 'a']++;
}
ArrayList<Point> a = new ArrayList<>();
for (int i = 0; i < c.length; i++) {
if(c[i] > 0)
a.add(new Point(i, c[i]));
}
if(a.size() > n){
out.println(-1);
}else{
int l = 1;
int h = s.length();
int r = -1;
while(l <= h){
int mid = (l + h)/2;
int x = 0;
for (int i = 0; i < 26; i++) {
if(c[i] > 0){
x += Math.max(1, (c[i] + mid - 1) / mid);
}
}
if(x <= n){
r = mid;
h = mid - 1;
}else{
l = mid + 1;
}
}
char[] ans = new char[n];
int[] used = new int[26];
int p = 0;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < (c[i] + r - 1) / r; j++) {
ans[p++] = (char)('a' + i);
}
}
for (int i = p; i < n; i++) {
ans[i] = 'a';
}
out.println(r);
for (int i = 0; i < ans.length; i++) {
out.print(ans[i]);
}
out.println();
}
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();}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | e62c6bb02dd84b8b48f2315a287897e9 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Abood3A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = sc.next();
int n = sc.nextInt();
int[] c = new int[26];
for (int i = 0; i < s.length(); i++) {
c[s.charAt(i) - 'a']++;
}
ArrayList<Point> a = new ArrayList<>();
for (int i = 0; i < c.length; i++) {
if(c[i] > 0)
a.add(new Point(i, c[i]));
}
if(a.size() > n){
out.println(-1);
}else{
int l = 1;
int h = s.length();
int r = -1;
while(l <= h){
int mid = (l + h)/2;
int x = 0;
for (int i = 0; i < 26; i++) {
if(c[i] > 0){
x += Math.max(1, (c[i] + mid - 1) / mid);
}
}
if(x <= n){
r = mid;
h = mid - 1;
}else{
l = mid + 1;
}
}
char[] ans = new char[n];
int[] used = new int[26];
int p = 0;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < (c[i] + r - 1) / r; j++) {
ans[p++] = (char)('a' + i);
}
}
for (int i = p; i < n; i++) {
ans[i] = 'a';
}
out.println(r);
for (int i = 0; i < ans.length; i++) {
out.print(ans[i]);
}
out.println();
}
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();}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 8 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 46b94cc0bf02e35985e5d5b82c6bb9ee | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
public class P335A {
private static class Letter implements Comparable<Letter> {
char c;
int total;
int occu;
public Letter(char c, int total, int occu) {
this.c = c;
this.total = total;
this.occu = occu;
}
@Override
public int compareTo(Letter other) {
float x1 = (float)total/occu;
float x2 = (float)(other.total)/other.occu;
if (x1 > x2) return -1;
if (x1 < x2) return 1;
if (c < other.c) return -1;
if (c > other.c) return 1;
return 0;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
final int N = sc.nextInt();
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!count.containsKey(c)) {
count.put(c, 0);
}
count.put(c, count.get(c) + 1);
}
int m = count.size();
if (m > N) {
System.out.println(-1);
return;
}
PriorityQueue<Letter> queue = new PriorityQueue<Letter>();
int[] occupied = new int[26];
for (char c: count.keySet()) {
occupied[c-'a'] = 1;
queue.add(new Letter(c, count.get(c), 1));
}
for (int i = 0; i < N - m; i++) {
Letter letter = queue.poll();
occupied[letter.c-'a']++;
queue.add(new Letter(letter.c, letter.total, letter.occu + 1));
}
Letter letter = queue.poll();
if (letter.total % letter.occu == 0) {
System.out.println(letter.total/letter.occu);
} else {
System.out.println(letter.total/letter.occu + 1);
}
StringBuilder sb = new StringBuilder();
for (char c: count.keySet()) {
for (int i = 0; i < occupied[c-'a']; i++) {
sb.append(c);
}
}
System.out.println(sb.toString());
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 01a18ff4628059da9ed39f1c1e1b41b6 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Banan {
public static class Letter implements Comparable<Letter>{
public Letter(char c, int count){
this.letter = c;
this.stickCount = 1;
this.str�ount = count;
}
char letter;
int str�ount;
int stickCount;
@Override
public int compareTo(Letter that) {
if(this.str�ount*that.stickCount > that.str�ount*this.stickCount) return -1;
else return 1;
}
}
public static void main(String[] args) throws IOException{
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
TreeSet<Letter> set = new TreeSet<Letter>();
int n = Integer.parseInt(reader.readLine());
int l = s.length();
int[] count = new int[26];
for(int i=0; i<l; i++){
char c = s.charAt(i);
count[c - 'a']++;
}
int total = 0;
for(int i=0;i<26;i++){
if(count[i]>0){
total++;
set.add(new Letter((char)(i+'a'), count[i]));
}
}
if(total > n){
System.out.println(-1);
}else{
while(total < n){
Letter lc = set.pollFirst();
lc.stickCount++;
total++;
set.add(lc);
}
int k = 0;
for(Letter lc:set){
if(((double)lc.str�ount)/lc.stickCount > k){
k = (int)Math.ceil(((double)lc.str�ount)/lc.stickCount);
}
}
System.out.println(k);
for(Letter lc:set){
for(int i=0;i<lc.stickCount;i++){
System.out.print(lc.letter);
}
}
System.out.println();
}
} finally {
if(reader != null)
reader.close();
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 5f459eb962cb835376c128f8a903a6b0 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
import java.io.*;
public class CodeForces {
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
int n = Integer.parseInt(in.readLine());
numStamp(s, n);
}
public static void numStamp(String s, int n) {
int[] letters = new int[26];
int num_letters = 0;
for (int i = 0; i < s.length(); i++) {
if (letters[s.charAt(i) - 'a'] == 0)
num_letters++;
letters[s.charAt(i) - 'a']++;
}
if (num_letters > n) {
System.out.println(-1);
return;
}
int[] ratios = new int[26];
double[] used = new double[26];
StringBuilder stamp = new StringBuilder("");
for (int letter = 0; letter < 26; letter++) {
ratios[letter] = letters[letter];
if (letters[letter] > 0) {
used[letter]++;
stamp.append( (char) (letter + 'a'));
}
}
for (int space = num_letters; space <= n; space++) {
int maxRatio = 0;
int maxInd = -1;
for (int letter = 0; letter < 26; letter++) {
if (ratios[letter] > maxRatio) {
maxRatio = ratios[letter];
maxInd = letter;
}
}
if (space == n) {
System.out.println(maxRatio);
System.out.println(stamp.toString());
}
used[maxInd]++;
stamp.append((char) (maxInd + 'a'));
ratios[maxInd] = (int) Math.ceil(letters[maxInd] / used[maxInd]);
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 2b0537bb5beecfc6b6ca832cb94d8b16 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class A {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
String goal = nextToken();
int[] count = new int[26];
for(int i = 0; i < goal.length(); i++) {
count[goal.charAt(i)-'a']++;
}
int numD = 0;
for(int out: count) {
if(out > 0) {
numD++;
}
}
int n = readInt();
if(numD > n) {
pw.println(-1);
}
else {
int min = 1;
int max = 10000;
while(min != max) {
int mid = (min+max)/2;
int use = 0;
for(int out: count) {
int must = (out+mid-1)/mid;
use += must;
}
if(use <= n) {
max = mid;
}
else {
min = mid+1;
}
}
pw.println(min);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < count.length; i++) {
int use = (count[i] + min-1) / min;
while(use-- > 0) {
sb.append((char)('a'+i));
}
}
while(sb.length() < n) {
sb.append("z");
}
pw.println(sb);
}
}
pw.close();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 2de2594117e6d228d0ea27d9ad57980c | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
int[] cnt;
int N;
public void solve() throws IOException {
cnt = new int[26];
char[] s = reader.readLine().toCharArray();
for(int i = 0; i < s.length; i++)
cnt[ s[i]-'a' ]++;
N = nextInt();
if( !OK(s.length)){
out.println(-1); return;
}
int l = 1;
int r = s.length;
while( l < r ){
int mid = (l+r)/2;
if( OK(mid) ){
r = mid;
}
else{
l = mid+1;
}
}
out.println(l);
int to = 0;
for(int i = 0; i < 26; i++){
int need = (int) Math.ceil( (double)cnt[i]/l );
for(int j = 0; j < need; j++){
out.print( (char)('a'+i) );
}
to += need;
}
for(int i = 0; i < N-to; i++)
out.print('a');
out.println();
}
public boolean OK(int v){
int len = 0;
for(int i = 0; i < 26; i++){
len += Math.ceil( (double)cnt[i]/v);
}
if( len <= N) return true;
return false;
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | b82079e7cfbcd4ddd56c6a8c7d7c29b2 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
public class maximus {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
String str=in.next();
int n=in.nextInt();
int array[]=new int[26];
for(int i=0;i<str.length();i++)array[str.charAt(i)-97]++;
int high=1001;
int low=0;
int cnt=0;
for(int i=0;i<26;i++)if(array[i]!=0)cnt++;
if(cnt>n)System.out.print("-1");
else{
int temp=0;
while(low<high){
int mid=(high+low)/2;
temp=0;
for(int i=0;i<26;i++)temp+=Math.ceil((double)array[i]/mid);
if(temp>n)low=mid+1;
else high=mid;
//System.out.println(low+" "+high+" "+temp);
}
temp=0;
for(int i=0;i<26;i++)temp+=Math.ceil((double)array[i]/(low));
if(temp<=n && low>0){
System.out.println(low);
StringBuilder sb=new StringBuilder();
for(int i=0;i<26;i++)
for(int j=0;j<Math.ceil((double)array[i]/low);j++)sb.append((char)(i+97));
for(int i=sb.length();i<n;i++)sb.append('a');
System.out.print(sb);
}
else{
System.out.println(low+1);
StringBuilder sb=new StringBuilder();
low++;
for(int i=0;i<26;i++)
for(int j=0;j<Math.ceil((double)array[i]/low);j++)sb.append((char)(i+97));
for(int i=sb.length();i<n;i++)sb.append('a');
System.out.print(sb);
}
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | b05ac8e9b8aa012e55cca0b48eb03fa0 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000009;
static ArrayList<Integer>[] g;
public static void main(String[] args) throws IOException
{
//Scanner input = new Scanner(new File("input.txt"));
//PrintWriter out = new PrintWriter(new File("output.txt"));
input.init(System.in);
PrintWriter out = new PrintWriter((System.out));
String s = input.next();
int n = input.nextInt();
int[] f = new int[26];
for(int i = 0; i<s.length(); i++) f[s.charAt(i)-'a']++;
int res = -1;
String str = "";
for(int i = 1; i<=1000; i++)
{
int x = 0;
for(int j = 0; j<26; j++)
{
if(f[j] == 0) continue;
x += (f[j]+i-1)/i;
}
if(x<=n)
{
res = i;
for(int j = 0; j<26; j++)
for(int k = 0; k<(f[j]+i-1)/i; k++)
str += (char)('a'+j);
break;
}
}
out.println(res);
if(res>-1)
{
while(str.length()<n) str+='a';
}
out.println(str);
out.close();
}
static long pow(long x, long p)
{
if(p==0) return 1;
if((p&1) > 0)
{
return (x*pow(x, p-1))%mod;
}
long sqrt = pow(x, p/2);
return (sqrt*sqrt)%mod;
}
static long gcd(long a, long b)
{
if(b==0) return a;
return gcd(b, a%b);
}
static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static String nextLine() throws IOException {
return reader.readLine();
}
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 202e75b60a21dfdbd466ffbf701851b7 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class A implements Runnable {
private void solve() throws IOException {
String s = nextToken();
int n = nextInt();
int[] f = new int[26];
int distincts = 0;
for (int i = 0; i < s.length(); i++) {
if (f[s.charAt(i) - 'a'] == 0) ++distincts;
f[s.charAt(i) - 'a']++;
}
if (distincts > n) {
pl(-1);
return;
}
boolean found = false;
String ret = "";
int len = -1;
int lo = 1, hi = s.length() + 1;
while (hi > lo) {
int i = (lo + hi) / 2;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < f.length; j++) {
if (f[j] > 0) {
int ns = (f[j] / i) + (f[j] % i == 0 ? 0 : 1);
while (ns-- > 0) sb.append((char) (j + 'a'));
}
}
if (sb.length() <= n) {
hi = i;
while (sb.length() < n)
sb.append("a");
if (sb.length() == n) {
found = true;
ret = sb.toString();
len = i;
}
} else {
lo = i + 1;
}
}
if (!found) {
pl(-1);
} else {
pl(len); pl(ret);
}
}
public static void main(String[] args) {
new A().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new BufferedReader(
new InputStreamReader(System.in)));
writer = new PrintWriter(System.out);
tokenizer = null;
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
void p(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
void pl(Object... objects) {
p(objects);
writer.println();
}
int cc;
void pf() {
writer.printf("Case #%d: ", ++cc);
}
} | Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | 601465c085d487d60fecf0cd164f3383 | train_002.jsonl | 1375549200 | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static class Pair implements Comparable<Pair> {
public char c;
public int f;
public Pair(char c, int f) {
this.c = c;
this.f = f;
}
public int compareTo(Pair pair) {
if (this.f < pair.f)
return 1;
if (this.f > pair.f)
return -1;
if (this.c < pair.c)
return -1;
if (this.c > pair.c)
return 1;
return 0;
}
}
public static void main(String[] args) throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] s = br.readLine().toCharArray();
int n = Integer.parseInt(br.readLine());
int[] f = new int[26];
List<Pair> list = new ArrayList<Pair>();
Arrays.fill(f, 0);
for (int i = 0; i < s.length; i++)
f[s[i]-'a']++;
int cnt = 0;
for (int i = 0; i < 26; i++)
if (f[i] > 0) {
list.add(new Pair((char) ('a' + i), f[i]));
cnt++;
}
Collections.sort(list);
if (cnt > n)
System.out.println("-1");
else
for (int k = 1;; k++) {
int need = 0;
for (Pair p : list) {
char cc = p.c;
int ff = p.f;
int nn = (p.f + k - 1) / k;
need += nn;
}
if (need <= n) {
StringBuilder sb = new StringBuilder();
for (Pair p : list) {
char cc = p.c;
int ff = p.f;
int nn = (p.f + k - 1) / k;
for (int i = 0; i < nn; i++)
sb.append(cc);
}
int rem = n - need;
for (int i = 0; i < rem; i++)
sb.append('z');
System.out.println(k);
System.out.println(sb.toString());
break;
}
}
}
}
| Java | ["banana\n4", "banana\n3", "banana\n2"] | 2 seconds | ["2\nbaan", "3\nnab", "-1"] | NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana". | Java 6 | standard input | [
"constructive algorithms",
"binary search",
"greedy"
] | f16f00edbc0c2e984caa04f71ae0324e | The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000). | 1,400 | On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1. | standard output | |
PASSED | de8eb990885e5c8b51c783c935850c32 | train_002.jsonl | 1312390800 | Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.Point;
// SHIVAM GUPTA :
//NSIT
//decoder_1671
// STOP NOT TILL IT IS DONE OR U DIE .
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
public class Main
{
// static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
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 int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
public static int mod(int x)
{
if(x <0)return -1*x ;
else return x ;
}
public static long mod(long x)
{
if(x <0)return -1*x ;
else return x ;
}
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
public static int countBits(long n)
{
int count = 0;
while (n != 0)
{
count++;
n = (n) >> (1L) ;
}
return count;
}
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
public static int min(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[0];
}
/////////////////////////////////////////////////////////////////////////////
public static int max(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[3];
}
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static boolean sameParity(long a ,long b )
{
long x = a% 2L; long y = b%2L ;
if(x==y)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a*b)/gc ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a*b)/gc ;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
public static void sortD(long[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
long temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 10000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
// The above code works well for n upto the order of 10^7.
// Beyond this we will face memory issues.
// Time Complexity: The precomputation for smallest prime factor is done in O(n log log n)
// using sieve.
// Where as in the calculation step we are dividing the number every time by
// the smallest prime number till it becomes 1.
// So, let’s consider a worst case in which every time the SPF is 2 .
// Therefore will have log n division steps.
// Hence, We can say that our Time Complexity will be O(log n) in worst case.
static Vector<Integer> getFactorization(int x)
{
Vector<Integer> ret = new Vector<>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
public static long binarySerachGreater(int[] arr , int start , int end , int val)
{
// fing total no of elements strictly grater than val in sorted array arr
if(start > end)return 0 ; //Base case
int mid = (start + end)/2 ;
if(arr[mid] <=val)
{
return binarySerachGreater(arr,mid+1, end ,val) ;
}
else{
return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ;
}
}
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(long x ,long n)
{
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n /= 2 ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
long res = 1;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x /= 2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod m.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long modBinomial(long n, long k, long p) {
// calculates C(n,k) mod p (assuming p is prime).
long numerator = 1; // n * (n-1) * ... * (n-k+1)
for (int i=0; i<k; i++) {
numerator = (numerator * (n-i) ) % p;
}
long denominator = 1; // k!
for (int i=1; i<=k; i++) {
denominator = (denominator * i) % p;
}
// numerator / denominator mod p.
return ( numerator* modInverse(denominator,p) ) % p;
}
/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
static ArrayList<Integer>[] tree ;
// static long[] child;
// static int mod= 1000000007 ;
// static int[][] pre = new int[3001][3001];
// static int[][] suf = new int[3001][3001] ;
//program to calculate noof nodes in subtree for every vertex including itself
public static void countNoOfNodesInsubtree(int child ,int par , int[] dp)
{
int count = 1 ;
for(int x : tree[child])
{
if(x== par)continue ;
countNoOfNodesInsubtree(x,child,dp) ;
count= count + dp[x] ;
}
dp[child] = count ;
}
public static void depth(int child ,int par , int[] dp , int d )
{
dp[child] =d ;
for(int x : tree[child])
{
if(x== par)continue ;
depth(x,child,dp,d+1) ;
}
}
public static void dfs(int sv , boolean[] vis)
{
vis[sv] = true ;
for(int x : tree[sv])
{
if( !vis[x])
{
dfs(x ,vis) ;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> listl = new ArrayList<>() ;
ArrayList<Integer> lista = new ArrayList<>() ;
ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
//HashMap<Integer,Integer> map = new HashMap<>() ;
HashMap<Character,Integer> map = new HashMap<>() ;
//HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> map1 = new HashMap<>() ;
HashMap<Integer,Integer> map2 = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
// Set<Long> set = new HashSet<>() ;
//Set<Integer> set = new HashSet<>() ;
Set<Character> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcases = 1;
//testcases = scn.nextInt() ;
for(int testcase =1 ; testcase <= testcases ;testcase++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
// int n = scn.nextInt() ;int m = scn.nextInt() ;
// tree = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// tree[i] = new ArrayList<Integer>();
// }
// for(int i = 0 ; i <= m-1 ; i++)
// {
// int fv = scn.nextInt()-1 ; int sv = scn.nextInt()-1 ;
// tree[fv].add(sv) ;
// tree[sv].add(fv) ;
// }
// boolean[] visited = new boolean[n] ;
// int ans = 0 ;
// for(int i = 0 ; i < n ; i++)
// {
// if(!visited[i])
// {
// dfs(i , visited ) ;
// ans++ ;
// }
// }
String s = scn.next() ;
int k = scn.nextInt() ;
int n = s.length() ;
Pair[] arr = new Pair[26] ;
for(int i = 0; i< 26 ; i++){arr[i] = new Pair() ; arr[i].first = (char)(i+97);}
for(int i = 0 ; i < n ;i++)
{
char temp = s.charAt(i) ;
int a = temp ;
a -= 97 ;
arr[a].second = arr[a].second +1 ;
}
Arrays.sort(arr, new Comparator<Pair>() {
@Override
public int compare(Pair a, Pair b) {
if (a. second != b.second) {
return a.second - b.second;
}
return a.first-b.first ;
}
});
int c= 0 ;
for(int i = 0 ; i < 26 ;i++)
{
if(arr[i].second == 0 )continue ;
if(arr[i].second + c > k)
{
break ;
}
else if(arr[i].second > 0 ){
c = c + arr[i].second ;
set.add(arr[i].first) ;
}
}
int[] f = new int[26] ;
c= 0 ;
for(int i = 0; i < n ;i++)
{
if(!set.contains(s.charAt(i)))
{
sb.append(s.charAt(i)) ;
int t = s.charAt(i) ;
t =t-97 ;
f[t]++ ;
}
}
for(int x : f)
{
if(x >0)c++ ;
}
out.println(c) ;out.println(sb) ;
sb.delete(0 , sb.length()) ;
list.clear() ;listb.clear() ;
map.clear() ;
map1.clear() ;
map2.clear() ;
set.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
char first ;
int second ;
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
| Java | ["aaaaa\n4", "abacaba\n4", "abcdefgh\n10"] | 2 seconds | ["1\naaaaa", "1\naaaa", "0"] | NoteIn the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string. | Java 11 | standard input | [
"greedy"
] | f023111561605b3e44ca85cb43b4aa00 | The first input data line contains a string whose length is equal to n (1 ≤ n ≤ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≤ k ≤ 105). | 1,200 | Print on the first line the only number m — the least possible number of different characters that could remain in the given string after it loses no more than k characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them. | standard output | |
PASSED | 7b0d8c9e235fba55d05a26256a01613a | train_002.jsonl | 1312390800 | Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String str = sc.next();
int k = sc.nextInt();
// Get Frequency Of Chars
int counter[] = new int[150];
for(int i = 0;i < str.length();i++) {
counter[str.charAt(i)]++;
}
while( k != 0 ) {
int min = (int) 1e6 + 1;
int id = 'a';
for(int i = 'a';i <= 'z';i++) {
if(counter[i] == 0) continue;
if(counter[i] < min) {
min = counter[i];
id = i;
}
}
if(k < min)
break;
k -= counter[id];
counter[id] = 0;
}
int res = 0;
for(int i = 'a';i <= 'z';i++) {
if(counter[i] > 0)
res++;
}
System.out.println(res);
if(res == 0)
System.out.println();
for(int i = 0;i < str.length();i++) {
if(counter[str.charAt(i)] == 0)
continue;
System.out.print(str.charAt(i));
}
}
} | Java | ["aaaaa\n4", "abacaba\n4", "abcdefgh\n10"] | 2 seconds | ["1\naaaaa", "1\naaaa", "0"] | NoteIn the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string. | Java 11 | standard input | [
"greedy"
] | f023111561605b3e44ca85cb43b4aa00 | The first input data line contains a string whose length is equal to n (1 ≤ n ≤ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≤ k ≤ 105). | 1,200 | Print on the first line the only number m — the least possible number of different characters that could remain in the given string after it loses no more than k characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them. | standard output | |
PASSED | 5a0c78382157f6701f1ae49eba4a8d5c | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Iterator;
public class acm_practice {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine(), " ");
int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); double k=Double.parseDouble(st.nextToken());
HashMap<String, Integer> map=new HashMap<>();
for(int i=0;i<n;i++) {
st = new StringTokenizer(bf.readLine(), " ");
String s=st.nextToken(); int u=Integer.parseInt(st.nextToken());
if(!map.containsKey(s)&&u*k+1e-9>=100) {
map.put(s, (int)(u*k+(1e-9)));
}
}
for(int i=0;i<m;i++) {
String s=bf.readLine();
if(map.containsKey(s)) {
// System.out.println(map.get(s));
int z=(int)(map.get(s)*k);
if(z>=100)
z++;
}else {
map.put(s, 0);
}
}
Collection c = map.keySet();
Iterator itr = c.iterator();
int j=0;
String x[]=new String[map.size()];
while (itr.hasNext()) {
x[j]=(String)itr.next();
j++;
}
Arrays.sort(x);
System.out.println(x.length);
for(int i=0;i<x.length;i++) {
System.out.println(x[i]+" "+map.get(x[i]));
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 1b671e616413b355b37b8f7026b1693b | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.*;
import java.util.*;
public class TestClass{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
double kd = Double.parseDouble(st.nextToken());
int k = (int)(Math.round(kd*100));
//System.out.println(k);
HashMap<String,Integer> map = new HashMap<>();
for(int i = 0; i<n; i++){
StringTokenizer st1 = new StringTokenizer(br.readLine());
String name = st1.nextToken();
int level = Integer.parseInt(st1.nextToken());
int new_level = (level*k);
//System.out.println(new_level);
new_level /= 100;
if(new_level >= 100){
map.put(name, new_level);
}
}
for(int i = 0; i<m; i++){
String name = br.readLine();
if(!map.containsKey(name)) {
map.put(name, 0);
}
}
ArrayList<String> names = new ArrayList<String>(map.keySet());
Collections.sort(names);
System.out.println(map.size());
for(String name: names) {
System.out.println(name+" "+map.get(name));
}
}
static class Skill{
String name;
int level;
public Skill(String s, int i){
name = s;
level = i;
}
public Skill(String s){
name = s;
level = 0;
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 0aa3601ab3e0c9cb0d299e5853237128 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int countCurrent = in.nextInt();
int countNext = in.nextInt();
int coef = (int)(in.nextDouble() * 100 + 1e-5);
List<Pair<String, Integer>> result = new ArrayList<Pair<String, Integer>>();
for (int i = 0; i < countCurrent; ++i) {
String name =in.nextString();
int cur = in.nextInt() * coef / 100;
if (cur < 100) {
continue;
}
result.add(Pair.makePair(name, cur));
}
for (int i = 0; i < countNext; ++i) {
String name = in.nextString();
boolean bad = false;
for (Pair<String, Integer> p : result) {
if (p.first.compareTo(name) == 0) {
bad = true;
break;
}
}
if (!bad) {
result.add(Pair.makePair(name, 0));
}
}
Collections.sort(result);
out.println(result.size());
for (Pair<String, Integer> p : result) {
out.println(p.first + " " + p.second);
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static<U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>)first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>)second).compareTo(o.second);
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | c2909d743412441d9867a4bcadd13725 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
public class transmigration {
// reading 53 01
// thinking 01 03
// coding 03 07
// debuging 07 09
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
String z = sc.next();
int kk = Integer.parseInt(z.substring(2));
// int kk= 0;
// double k = sc.nextDouble();
// int kk=(int)( k*100);
TreeMap<String, Integer> hm = new TreeMap<>();
for (int i=0;i<n;i++) {
String s = sc.next();
int x = sc.nextInt();
int xA = (x*kk)/100;
// System.out.println(kk);
if (xA >=100) {
hm.put(s, xA);
}
}
for (int i=0;i<m;i++) {
String s = sc.next();
if (!hm.containsKey(s)) {
hm.put(s, 0);
}
}
sc.close();
System.out.println(hm.size());
for (String s : hm.keySet()) {
System.out.println(s+" "+hm.get(s));
}
// System.out.println(8700*0.94);
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 1d8d1181196703ced1019b2e073576d6 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.Scanner;
import java.util.TreeMap;
import java.util.Map.Entry;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeMap<String, Integer> skills = new TreeMap<>();
int n = sc.nextInt(), m = sc.nextInt(), k = (int)Math.round(sc.nextDouble() * 100);
for(int i = 0; i < n; i++) {
String s = sc.next();
int x = (int)(sc.nextInt() * k / 100.0);
if(x < 100)
continue;
skills.put(s, x);
}
for(int i = 0; i < m; i++) {
String s = sc.next();
if(!skills.containsKey(s))
skills.put(s, 0);
}
System.out.println(skills.size());
while(!skills.isEmpty()) {
Entry<String, Integer> entry = skills.pollFirstEntry();
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | dd49bd597e7ab21114fb36eef3a5fbfa | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class E {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), m = sc.nextInt();
int k = Integer.parseInt(sc.next().substring(2));
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
while(n-->0)
{
String s = sc.next();
int x = (sc.nextInt() * k) / 100;
if(x >= 100)
map.put(s, x);
}
while(m-->0)
{
String s = sc.next();
if(!map.containsKey(s))
map.put(s, 0);
}
StringBuilder sb = new StringBuilder();
sb.append(map.size()+"\n");
for(Entry<String, Integer> e: map.entrySet())
sb.append(e.getKey() + " " + e.getValue() + "\n");
out.print(sb);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 0498cee38be53bd0723ede81a77d0640 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | //package CodeForces;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class Transmigration {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
double k=s.nextDouble();
HashMap<String,Integer> map=new HashMap<>();
ArrayList<String> arr=new ArrayList<String>();
for(int i=0;i<n;i++)
{
String str=s.next();
int temp=s.nextInt();
BigDecimal small=new BigDecimal((double)temp*k);
if(small.doubleValue()>=100)
{
map.put(str,temp);
arr.add(str);
}
}
for(int i=0;i<m;i++)
{
String str=s.next();
if(!map.containsKey(str))
{
arr.add(str);
}
}
Collections.sort(arr);
System.out.println(arr.size());
for(int i=0;i<arr.size();i++)
{
String str=arr.get(i);
if(map.containsKey(str))
{
BigDecimal small=new BigDecimal(String.format("%.2f",(double)map.get(str)*k));
if(small.doubleValue()>=100)
{
System.out.println(str+" "+(int)small.doubleValue());
}
}
else
{
System.out.println(str+" "+0);
}
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 58b4113b2ddbb3133c42b379ed4d99f4 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Transmigration {
static double eps=1e-9;
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
double k=sc.nextDouble();
ArrayList<skill> s=new ArrayList<skill>();
HashSet<String>set=new HashSet<String>();
for(int i=0;i<n;++i) {
String nm=sc.next();
int l=sc.nextInt();
if((int)l*k+eps>=100) {
set.add(nm);//System.out.println(l*k+eps);
s.add(new skill(nm,(int) (l*k+eps)));
}
}
for(int i=0;i<m;++i) {
String nm=sc.next();
if(!set.contains(nm))
s.add(new skill(nm,0));
}
Collections.sort(s);
System.out.println(s.size());
for(int i=0;i<s.size();++i) {
System.out.println(s.get(i).name+" "+s.get(i).lvl);
}
}
static class skill implements Comparable<skill>{
String name;
int lvl;
public skill(String s,int a) {
name=s;
lvl=a;
}
public int compareTo(skill b) {
return name.compareTo(b.name);
}
}
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();}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 49974fdc1840c8405072f5448b576bdb | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class transmigration {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int skills = s.nextInt();
int skillst = s.nextInt();
double d = s.nextDouble();
TreeMap<String, Integer> hm = new TreeMap<String,Integer>();
while(skills-- >0){
String sk = s.next();
int level = s.nextInt();
if(Math.floor(level*d)>=100){
hm.put(sk,(int) ((float)(level*d)));
}
}
while(skillst-- >0){
String sk = s.next();
if(!hm.containsKey(sk))
hm.put(sk,0);
}
System.out.println(hm.size());
for(Map.Entry<String, Integer> e :hm.entrySet()){
System.out.println(e.getKey() +" "+e.getValue());
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 5f3f4b59c64358dcd40c5b58cf2d3d9c | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
String k=st.nextToken();
int k2=Integer.parseInt(k.substring(2,k.length()));
TreeMap<String ,Integer>shagara=new TreeMap<>();
for (int i = 0; i < n; i++) {
st=new StringTokenizer(br.readLine());
String name=st.nextToken();
int level=(Integer.parseInt(st.nextToken())*k2)/100;
if(level>=100){
shagara.put(name,level);
}
}
for (int i = 0; i < m; i++) {
String name=br.readLine();
if(!shagara.containsKey(name))
shagara.put(name,0);
}
out.println(shagara.size());
for (Map.Entry e:shagara.entrySet()) {
out.println(e.getKey()+" "+e.getValue());
}
out.flush();
}
} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | b81de8a5839e5ad9da746bcbdd3355fb | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mouna Cheikhna
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = Integer.parseInt(in.next().substring(2));
Map<String, Integer> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
String name = in.next();
int capacity = (in.nextInt() * k) / 100;
if (capacity >= 100) {
map.put(name, capacity);
}
}
for (int i = 0; i < m; i++) {
String name = in.next();
if (!map.containsKey(name)) {
map.put(name, 0);
}
}
out.println(map.size());
for (Map.Entry<String, Integer> entry : map.entrySet()) {
out.println(entry.getKey() + " " + entry.getValue());
}
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 78149bcbbb07124295044e1767cb77d8 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.*;
import java.io.*;
public class transmigration {
public static String toString(skill o){
return o.name + " " + o.exp;
}
static class skill implements Comparable<skill>{
String name; int exp;
public skill(String name, int exp){
this.name = name; this.exp = exp;
}
public int compareTo(skill o){
for(int i = 0; i<name.length() && i<o.name.length(); i++){
if(name.charAt(i)>o.name.charAt(i)){return 1;}
else{if (name.charAt(i) < o.name.charAt(i)){return -1;}
}
if(i==o.name.length()-1){return 1;}
}
return -1;
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int firstskills = sc.nextInt(); int secondskills = sc.nextInt(); double reduction = sc.nextDouble();
skill[] premierskills = new skill[firstskills]; //HashSet<String> newskills = new HashSet<>();
ArrayList<String> newwskills = new ArrayList<>(); ArrayList<skill> finalskills = new ArrayList<>();
for(int i = 0; i<firstskills; i++){premierskills[i] = new skill(sc.next(), sc.nextInt());}
for(int i = 0; i<secondskills; i++){newwskills.add(sc.next());}
//for(int i = 0; i<premierskills.length; i++){out.println(toString(premierskills[i]));}
//for(int i = 0; i<secondskills; i++){out.println(newwskills.get(i));}
for(int i = 0; i<firstskills; i++){
if(premierskills[i].exp*reduction>=100){
double newexp = premierskills[i].exp*reduction+0.000001; int intnewexp =(int) newexp;
skill item = new skill(premierskills[i].name, intnewexp);
finalskills.add(item);
}
}
for(int i = 0; i<secondskills; i++){
boolean itexists = false;
for(int j = 0; j<finalskills.size(); j++){
if(newwskills.get(i).equals(finalskills.get(j).name)){itexists = true;}
}
if(!itexists){ skill item = new skill(newwskills.get(i), 0); finalskills.add(item);}
}
Collections.sort(finalskills);
out.println(finalskills.size());
for(int i = 0; i<finalskills.size(); i++){out.println(toString(finalskills.get(i)));}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | b520c5d6877b3475d3b9be3b2f6cd846 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.*;
import java.math.BigDecimal;
public class HelloWorld{
static class pair{
String a;
int b;
}
public static void main(String []args){
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
double k=s.nextDouble();
pair[] arr=new pair[n];
HashMap<String,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
pair temp=new pair();
temp.a=s.next();
temp.b=s.nextInt();
arr[i]=temp;
}
String[] power=new String[m];
ArrayList<pair> ans=new ArrayList<>();
for(int i=0;i<m;i++){
power[i]=s.next();
}
for(int i=0;i<n;i++){
BigDecimal d=new BigDecimal(String.format("%.2f", k*arr[i].b));
if(d.doubleValue()>=100){
pair temp=new pair();
temp.a=arr[i].a;
temp.b=(int)d.doubleValue();
ans.add(temp);
map.put(temp.a,1);
}
}
for(int i=0;i<m;i++){
if(!map.containsKey(power[i])){
pair temp=new pair();
temp.a=power[i];
temp.b=0;
ans.add(temp);
}
}
Collections.sort(ans,new
Comparator<pair>(){
public int compare(pair x,pair y){
return x.a.compareTo(y.a);
}
});
System.out.println(ans.size());
for(int i=0;i<ans.size();i++){
System.out.println(ans.get(i).a+" "+ans.get(i).b);
}
}
} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | deb4c3e03b40ade98c6a505ebffd89b3 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.TreeMap;
public class Transmigration {
public static void main(String[] args) throws IOException {
BufferedReader axa = new BufferedReader(new InputStreamReader(System.in));
String [] te = axa.readLine().split(" ");
int have = Integer.parseInt(te[0]);
int neww = Integer.parseInt(te[1]);
int factor = (Integer.parseInt(te[2].substring(2)));
TreeMap<String, Integer> tmin = new TreeMap<>();
for(int i = 0 ; i<have;i++){
String[]temp = axa.readLine().split(" ");
int sl = (Integer.parseInt(temp[1])*factor)/100;
if(sl>=100){
tmin.put(temp[0], sl);
}
}
for(int i = 0 ;i<neww ; i++){
String tem = axa.readLine();
if(!tmin.containsKey(tem)){
tmin.put(tem, 0);
}
}
int n = tmin.size();
System.out.println(n);
for(int i = 0 ; i<n;i++ ){
System.out.println(tmin.firstKey()+" " +tmin.get(tmin.firstKey()) );
tmin.remove(tmin.firstKey());
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | c22217d1736ab4fe84f652a2d9d86507 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
Scanner sc=new Scanner(System.in);
StringBuilder sb=new StringBuilder();
PrintWriter out= new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
double k=sc.nextDouble();
TreeSet<hero> ts=new TreeSet<>();
HashSet<String> hs=new HashSet<>();
for (int i=0;i<n;i++) {
hero h=new hero(sc.next(), sc.nextInt());
double c=h.hp*k;
h.hp*=k;
if ((h.hp+1-c)<=1e-5)
h.hp++;
if (h.hp>=100) {
ts.add(h);
hs.add(h.name);
}
}
for (int i=0;i<m;i++) {
String x=sc.next();
if (!hs.contains(x)) {
ts.add(new hero(x,0));
}
}
out.println(ts.size());
for(hero x:ts) {
out.println(x.name+" "+x.hp);
}
out.flush();
}
static class hero implements Comparable<hero>{
String name;
int hp;
hero(String s , int h){
name=s;
hp=h;
}
@Override
public int compareTo(hero o) {
return name.compareTo(o.name);
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput() throws InterruptedException {Thread.sleep(3000);}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | b2dcc0593b6fdff2d1c3d67c284173b8 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class ChatOrder {
public static void main(String[] args) throws IOException {
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
double k = sc.nextDouble();
TreeSet<skill> tree = new TreeSet<skill>();
for (int i=0 ;i<n;i++){
String name =sc.next();
int pow = sc.nextInt();
pow = (int) (k*pow+1e-6);
if (pow >=100){
tree.add(new skill (name,pow));
}
}
for (int i = 0 ;i<m;i++){
String name = sc.next();
tree.add(new skill (name,0 ));
}
System.out.println(tree.size());
for (skill l :tree ){
l.disp();
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput() throws InterruptedException {Thread.sleep(3000);}
}
}
class skill implements Comparable<skill>{
private String s;
private int x ;
public skill (String s , int x){
this.s = s ;
this.x = x ;
}
public int compareTo(skill a2) {
return this.s.compareTo(a2.s);
}
public void disp(){
System.out.println (s + " "+x);
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | bd6cb2378c34c47ec604ca2001efa0f5 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.*;
import java.util.*;
public class A105
{
static class Skill implements Comparable<Skill>
{
String s ;
int e;
public Skill(String s , int e)
{
this.s=s;
this.e=e;
}
public int compareTo(Skill h)
{
return s.compareTo(h.s);
}
public String toString()
{
return s+" "+e;
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken().substring(2));
ArrayList<Skill> a = new ArrayList<Skill>();
for(int i =0 ;i<n ;i++)
{
st = new StringTokenizer(br.readLine());
a.add(new Skill(st.nextToken(),(Integer.parseInt(st.nextToken())*k/100)));
}
for(int i =0 ;i<a.size();)
if(a.get(i).e<100)
a.remove(i);
else i++;
loop:
for(int i=0;i<m;i++)
{
String x = br.readLine();
Skill s = new Skill(x,0);
for(Skill p : a)
if(x.equals(p.s))
continue loop;
a.add(s);
}
Collections.sort(a);
System.out.println(a.size());
for(Skill s : a)
System.out.println(s);
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 046294b0fad57681fa2f1b9ecef1aff6 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Set;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
double k = Double.parseDouble(st.nextToken());
TreeMap<String, Integer> skills = new TreeMap<>();
int counter = 0;
for (int i = 0 ; i<n ; i++){
st = new StringTokenizer(br.readLine());
String s = st.nextToken();
int v = Integer.parseInt(st.nextToken());
double temp = k*v;
int g = (int)(k*v);
if(temp-g>0.9999) g++;
if(g<100) continue;
skills.put(s,g);
counter++;
}
for (int i = 0 ; i< m ; i++){
String current = br.readLine();
if(!skills.containsKey(current)) {
counter ++;
skills.put(current, 0);
}
}
Set set = skills.entrySet();
Iterator it = set.iterator();
out.println(counter);
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
out.println(me.getKey() + " " + me.getValue());
}
out.flush();
out.close();
}} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 0631de5c4ad0ecd3ef3123f054392728 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class transmigration {
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
public static void main(String []args) throws IOException {
PrintWriter pw =new PrintWriter(System.out);
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m =sc.nextInt();
double k= sc.nextDouble();
TreeMap<String,Integer >tm=new TreeMap<>();
TreeMap<String,Integer >tmr=new TreeMap<>();
String a[]=new String [m];
for(int i=0;i<n;i++)tm.put(sc.next(), sc.nextInt());
for (int i=0;i<m;i++) a[i]=sc.next();
for(int i=0;i<m;i++) {
if(tm.containsKey(a[i])) {
if(tm.get(a[i])*k<100)tmr.put(a[i],0);
else
tmr.put(a[i], (int) (tm.get(a[i])*k+0.0000001));
tm.remove(a[i]);}
else
tmr.put(a[i], 0);
}
while(!tm.isEmpty()) {
if(tm.get(tm.firstKey())*k>=100)
tmr.put(tm.firstKey(), (int) (tm.get(tm.firstKey())*k+0.000001));
tm.pollFirstEntry();
}
pw.println(tmr.size());
while(!tmr.isEmpty()) {
pw.println(tmr.firstKey()+" "+tmr.get(tmr.firstKey()));
tmr.pollFirstEntry();
pw.flush();
}
}}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | bbcaa72a410043da96b0b786c3084b06 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static Scanner sc = new Scanner(System.in);
/*public static void main(String[] args) throws IOException {
int n= sc.nextInt();
boolean[] horrizontal= new boolean[n+1];
boolean[] verticle= new boolean[n+1];
for(int i=1; i<=(n*n); i++)
{
int h=sc.nextInt();
int v=sc.nextInt();
if(!horrizontal[h] && !verticle[v])
{
horrizontal[h]=true;
verticle[v]=true;
System.out.print(i + " ");
}
}
}*/
static int[] a;
static int count=0;
public static void binarySearch(int f, int l,int m)
{
if(f==l)
{
if(a[f]>m)
System.out.println(f);
else
System.out.println(f+1);return;
}
count++;
//System.out.println(Arrays.toString(a));
//System.out.println("f: " + f + " l: " + l);
int middle=(f+l)/2;
//System.out.println("middle: " + middle);
if(a[middle]<=m)
{
if(middle+1>l)
{
binarySearch(l,l,m);return;
}
binarySearch(middle+1,l,m);return;
}
if(middle-1<f)
{
binarySearch(f,f,m);return;
}
binarySearch(f,middle-1,m);
}
/*public static void main(String[] args) throws IOException {
int n=sc.nextInt();
a =new int[n];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
Arrays.sort(a);
int q=sc.nextInt();
for(int i=0; i<q; i++)
{
int m=sc.nextInt();
if(m>=a[a.length-1])
{
System.out.println(a.length);
}
else if(m<a[0])
{
System.out.println(0);
}
else
{
binarySearch(0, a.length-1,m);
}
}
}*/
/*public static void main(String[] args) throws IOException {
int n=sc.nextInt();
TreeSet<Chat> chatLog= new TreeSet<Chat>();
TreeMap<String, Chat> exists=new TreeMap<String, Chat>();
for(int i=1; i<=n;i++)
{
String s=sc.next();
if(exists.containsKey(s))
{
Chat temp=exists.get(s);
chatLog.remove(temp);
}
Chat c= new Chat(s,i);
exists.put(s,c);
chatLog.add(c);
}
for(Chat c: chatLog)
{
System.out.println(c.name);
}
}*/
public static void main(String[] args) throws IOException {
TreeMap<String, Integer> map= new TreeMap<String, Integer>();
int n=sc.nextInt();
int m=sc.nextInt();
double k=sc.nextDouble();
for (int i = 0; i < n; i++) {
String s=sc.next();
int v=sc.nextInt();
v=(int)(float)(v*k);
if(v>=100)
map.put(s, v);
}
for(int i=0; i<m; i++)
{
String s=sc.next();
if(!map.containsKey(s))
map.put(s, 0);
}
System.out.println(map.size());
for(Entry<String, Integer> e: map.entrySet())
{
System.out.println(e.getKey() + " " + e.getValue());
}
}
static class Chat implements Comparable<Chat>
{
String name;
int time;
public Chat(String n, int t)
{
name=n;
time=t;
}
public int compareTo(Chat c) {
return c.time-this.time;
}
}
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();
}
}
}
| Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | ef0810365304420e2175a2e22aa39c87 | train_002.jsonl | 1313247600 | In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static Scanner sc = new Scanner(System.in);
/*public static void main(String[] args) throws IOException {
int n= sc.nextInt();
boolean[] horrizontal= new boolean[n+1];
boolean[] verticle= new boolean[n+1];
for(int i=1; i<=(n*n); i++)
{
int h=sc.nextInt();
int v=sc.nextInt();
if(!horrizontal[h] && !verticle[v])
{
horrizontal[h]=true;
verticle[v]=true;
System.out.print(i + " ");
}
}
}*/
static int[] a;
static int count=0;
public static void binarySearch(int f, int l,int m)
{
if(f==l)
{
if(a[f]>m)
System.out.println(f);
else
System.out.println(f+1);return;
}
count++;
//System.out.println(Arrays.toString(a));
//System.out.println("f: " + f + " l: " + l);
int middle=(f+l)/2;
//System.out.println("middle: " + middle);
if(a[middle]<=m)
{
if(middle+1>l)
{
binarySearch(l,l,m);return;
}
binarySearch(middle+1,l,m);return;
}
if(middle-1<f)
{
binarySearch(f,f,m);return;
}
binarySearch(f,middle-1,m);
}
/*public static void main(String[] args) throws IOException {
int n=sc.nextInt();
a =new int[n];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
Arrays.sort(a);
int q=sc.nextInt();
for(int i=0; i<q; i++)
{
int m=sc.nextInt();
if(m>=a[a.length-1])
{
System.out.println(a.length);
}
else if(m<a[0])
{
System.out.println(0);
}
else
{
binarySearch(0, a.length-1,m);
}
}
}*/
/*public static void main(String[] args) throws IOException {
int n=sc.nextInt();
TreeSet<Chat> chatLog= new TreeSet<Chat>();
TreeMap<String, Chat> exists=new TreeMap<String, Chat>();
for(int i=1; i<=n;i++)
{
String s=sc.next();
if(exists.containsKey(s))
{
Chat temp=exists.get(s);
chatLog.remove(temp);
}
Chat c= new Chat(s,i);
exists.put(s,c);
chatLog.add(c);
}
for(Chat c: chatLog)
{
System.out.println(c.name);
}
}*/
public static void main(String[] args) throws IOException {
TreeMap<String, Integer> map= new TreeMap<String, Integer>();
int n=sc.nextInt();
int m=sc.nextInt();
double k=sc.nextDouble();
for (int i = 0; i < n; i++) {
String s=sc.next();
int v=sc.nextInt();
v=(int)(float)(v*k);
if(v>=100)
map.put(s, v);
}
for(int i=0; i<m; i++)
{
String s=sc.next();
if(!map.containsKey(s))
map.put(s, 0);
}
System.out.println(map.size());
for(Entry<String, Integer> e: map.entrySet())
{
System.out.println(e.getKey() + " " + e.getValue());
}
}
public static void solve(int[][]a, int i)
{
boolean zeroes=true;
for (int j = 0; j < a.length; j++) {
for (int j2 = 0; j2 < a.length; j2++) {
if(a[j][j2]==1)
{
zeroes=false;
}
}
}
if(zeroes)
{
System.out.println(i);return;
}
int[][] b= new int[3][3];
b[0][0]=(a[0][1] + a[1][0])%2;
b[0][1]=(a[0][0] + a[0][2] + a[1][1])%2;
b[0][2]=(a[0][1] + a[1][2])%2;
b[1][0]=(a[0][0] + a[2][0] + a[1][1])%2;
b[1][1]=(a[1][0] + a[0][1] + a[1][2] + a[2][1])%2;
b[1][2]=(a[0][2] + a[2][2] + a[1][1])%2;
b[2][0]=(a[1][0] + a[2][1])%2;
b[2][1]=(a[2][0] + a[1][1] + a[2][2])%2;
b[2][2]=(a[2][1] + a[1][2])%2;
//System.out.println(Arrays.toString( b[0]));
//System.out.println(Arrays.toString(b[1]));
//System.out.println(Arrays.toString(b[2]));
//System.out.println();
solve(b,i+1);
}
static class Chat implements Comparable<Chat>
{
String name;
int time;
public Chat(String n, int t)
{
name=n;
time=t;
}
public int compareTo(Chat c) {
return c.time-this.time;
}
}
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();
}
}
} | Java | ["5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost"] | 2 seconds | ["6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0"] | null | Java 8 | standard input | [
"implementation"
] | 7da1a5c4c76540e1c7dc06e4c908c8b4 | The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names. | 1,700 | Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order. | standard output | |
PASSED | 1f76e08eee45b5e84d490af8d1f1462c | train_002.jsonl | 1567175700 | Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;
import static java.lang.Integer.max;
public class Main implements Runnable, AutoCloseable {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
public static int lower_bound(int[] arr, int target) { //找到第一个大于等于x的数的位置
int l = 0;
int r = arr.length;
while (l < r) {
int mid = l + (r - l) / 2;
if (arr[mid] >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return l == arr.length ? -1 : l;
}
SortedSet<Integer> set;
public int[] solve(int[] array) {
set = new TreeSet<Integer>();
//利用TreeSet可以同时实现排序和去重 可以代替c++中的unique实现
for (int i = 0; i < array.length; ++i) {
set.add(array[i]);
}
//Integer[] b=(Integer[])set.toArray();
int[] b = new int[set.size()]; //将去重排序的数组赋值给b数组
int ct = 0;
for (int cur : set) {
b[ct++] = cur;
}
for (int i = 0; i < array.length; ++i) {
array[i] = lower_bound(b, array[i]) + 1; //利用lower_bound找到该数值的排位(rank)
//排名代表大小 越前越小 越后越大
}
//10000000,2,2,123123213离散化成2,1,1,3
return array;
}
@Override
public void run() {
int t = in.nextInt();
// int t = 1;
for (int i = 0; i < t; i++) {
doOnce();
}
}
private void doOnce() {
// int n = 15000;
// int[] a = new int[n];
// int maxa;
// int ansa = 0;
// for (int i = 0; i < n; i++) {
// a[i] = i;
// }
int n = in.nextInt();
int[] a = new int[n];
int maxa;
int ansa = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
// TreeSet<Integer> set = new TreeSet<>();
// for (int i = 0; i < n; i++) {
// set.add(a[i]);
// }
// for (int i = 0; i < n; i++) {
// a[i] = set.subSet(-1, a[i]).size() + 1;
// }
a = solve(a);
maxa = set.size();
int[] b = new int[maxa + 8];
for (int i = 0; i < n; i++) {
b[a[i]] = Math.max(b[a[i]], i);
}
for (int i = 1; i <= maxa; i++) {
b[i] = max(b[i - 1], b[i]);
}
for (int i = 0; i < n; i++) {
if (b[a[i] - 1] > i) {
ansa++;
}
}
out.println(ansa);
}
// if (test(n, m, k)) {
// out.println("YES");
// } else {
// out.println("NO");
// }
public static void main(String[] args) {
try (Main main = new Main()) {
main.run();
}
}
@Override
public void close() {
out.close();
}
} | Java | ["5\n6\n3 9 4 6 7 5\n1\n1000000\n2\n2 1\n10\n31 41 59 26 53 58 97 93 23 84\n7\n3 2 1 2 3 4 5"] | 1 second | ["3\n0\n1\n8\n2"] | null | Java 8 | standard input | [
"data structures",
"implementation"
] | 09faf19627d2ff00c3821d4bc2644b63 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$. | 1,100 | Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set. | standard output | |
PASSED | 6524a7f13f9f6ae5104c41e8392ad61a | train_002.jsonl | 1567175700 | Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets. | 256 megabytes | //import java.util.Arrays;
import java.util.Scanner;
public class SecondTask {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t =in.nextInt();
for(int i=0;i<t;i++) {
int n = in.nextInt();
int[] num = new int[n];
for(int j=0;j<n; j++){
num[j]=in.nextInt();
}
int k=0;
int min=num[n-1];
for(int x=n-2;x>=0;x--){
if(num[x]>min){
k++;}else{
min=num[x];
}
}
System.out.println(k);
}
}
}
| Java | ["5\n6\n3 9 4 6 7 5\n1\n1000000\n2\n2 1\n10\n31 41 59 26 53 58 97 93 23 84\n7\n3 2 1 2 3 4 5"] | 1 second | ["3\n0\n1\n8\n2"] | null | Java 8 | standard input | [
"data structures",
"implementation"
] | 09faf19627d2ff00c3821d4bc2644b63 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$. | 1,100 | Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set. | standard output | |
PASSED | 90eecfea61fa11d4d0495660129ce2a1 | train_002.jsonl | 1567175700 | Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets. | 256 megabytes | 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 BadPrices
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=0;
t=sc.nextInt();
while(t-->0)
{
int n=0;
n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int c=0;
int min=a[n-1];
for(int i=n-2;i>=0;i--)
{
if(a[i]>min)
c++;
min=(int)Math.min(a[i],min);
}
System.out.println(c);
}
}
} | Java | ["5\n6\n3 9 4 6 7 5\n1\n1000000\n2\n2 1\n10\n31 41 59 26 53 58 97 93 23 84\n7\n3 2 1 2 3 4 5"] | 1 second | ["3\n0\n1\n8\n2"] | null | Java 8 | standard input | [
"data structures",
"implementation"
] | 09faf19627d2ff00c3821d4bc2644b63 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$. | 1,100 | Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set. | standard output | |
PASSED | b70f2e453a24d4fa5464101c93da2514 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
//class Declaration
static class pair implements Comparable < pair > {
int x;
int y;
pair(int i, int j) {
x = i;
y = j;
}
public int compareTo(pair p) {
if (this.x != p.x) {
return this.x - p.x;
} else {
return this.y - p.y;
}
}
public int hashCode() {
return (x + " " + y).hashCode();
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
pair x = (pair) o;
return (x.x == this.x && x.y == this.y);
}
}
// int[] dx = {0,0,1,-1};
// int[] dy = {1,-1,0,0};
// int[] ddx = {0,0,1,-1,1,-1,1,-1};
// int[] ddy = {1,-1,0,0,1,-1,-1,1};
long mod = (long) 1e9 + 7;
int inf = (int) 1e9 + 5;
ArrayList < ArrayList < Integer >> g;
int[] col;
boolean vis[];
int[] subTreeBlackNodes, subTreeWhiteNodes;
int[] par;
void solve() throws Exception {
int n = ni();
vis = new boolean[n + 1];
subTreeBlackNodes = new int[n + 1];
subTreeWhiteNodes = new int[n + 1];
col = new int[n + 1];
par = new int[n + 1];
PriorityQueue < pair > pq = new PriorityQueue<>();
for (int i = 1; i <= n; ++i) {
pq.add(new pair(ni(), i));
int b = ni(), c = ni();
if (b != c) {
col[i] = b;
} else col[i] = -1;
}
//graph input
g = ng(n, n - 1);
int white = 0, black = 0;
for (int i = 1; i <= n; ++i) {
if (col[i] == 0) white++;
if (col[i] == 1) black++;
}
if (black != white) {
pn(-1);
} else {
// parent finding dfs ;
dfs_par(1, 1);
long ans = 0;
while (!pq.isEmpty()) {
pair p = pq.poll();
if (vis[p.y]) continue;
dfs_cnt_white_black(p.y, par[p.y]);
long shuffleNodes = Math.min(subTreeWhiteNodes[p.y], subTreeBlackNodes[p.y]);
subTreeBlackNodes[p.y] -= shuffleNodes;
subTreeWhiteNodes[p.y] -= shuffleNodes;
ans += ((long) p.x * shuffleNodes * 2L);
}
pn(ans);
}
}
void dfs_cnt_white_black(int s, int p) {
if (vis[s]) {
return;
}
vis[s] = true;
subTreeBlackNodes[s] += (col[s] == 1 ? 1 : 0);
subTreeWhiteNodes[s] += (col[s] == 0 ? 1 : 0);
for (int x: g.get(s)) {
if (x == p) continue;
dfs_cnt_white_black(x, s);
subTreeBlackNodes[s] += subTreeBlackNodes[x];
subTreeWhiteNodes[s] += subTreeWhiteNodes[x];
}
}
void dfs_par(int s, int p) {
par[s] = p;
for (int x: g.get(s)) {
if (x == p) continue;
dfs_par(x, s);
}
}
long pow(long a, long b) {
long result = 1;
while (b > 0) {
if (b % 2 == 1) result = (result * a) % mod;
b /= 2;
a = (a * a) % mod;
}
return result;
}
void print(Object o) {
System.out.println(o);
System.out.flush();
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
//output methods
private void pn(Object o) {
out.println(o);
}
private void p(Object o) {
out.print(o);
}
private ArrayList < ArrayList < Integer >> ng(int n, int e) {
ArrayList < ArrayList < Integer >> g = new ArrayList < > ();
for (int i = 0; i <= n; ++i) g.add(new ArrayList < > ());
for (int i = 0; i < e; ++i) {
int u = ni(), v = ni();
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private ArrayList < ArrayList < pair >> nwg(int n, int e) {
ArrayList < ArrayList < pair >> g = new ArrayList < > ();
for (int i = 0; i <= n; ++i) g.add(new ArrayList < > ());
for (int i = 0; i < e; ++i) {
int u = ni(), v = ni(), w = ni();
g.get(u).add(new pair(w, v));
g.get(v).add(new pair(w, u));
}
return g;
}
//input methods
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 void tr(Object...o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
void watch(Object...a) throws Exception {
int i = 1;
print("watch starts :");
for (Object o: a) {
//print(o);
boolean notfound = true;
if (o.getClass().isArray()) {
String type = o.getClass().getName().toString();
//print("type is "+type);
switch (type) {
case "[I":
{
int[] test = (int[]) o;
print(i + " " + Arrays.toString(test));
break;
}
case "[[I":
{
int[][] obj = (int[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[J":
{
long[] obj = (long[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[J":
{
long[][] obj = (long[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[D":
{
double[] obj = (double[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[D":
{
double[][] obj = (double[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[Ljava.lang.String":
{
String[] obj = (String[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[Ljava.lang.String":
{
String[][] obj = (String[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[C":
{
char[] obj = (char[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[C":
{
char[][] obj = (char[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
default:
{
print(i + " type not identified");
break;
}
}
notfound = false;
}
if (o.getClass() == ArrayList.class) {
print(i + " al: " + o);
notfound = false;
}
if (o.getClass() == HashSet.class) {
print(i + " hs: " + o);
notfound = false;
}
if (o.getClass() == TreeSet.class) {
print(i + " ts: " + o);
notfound = false;
}
if (o.getClass() == TreeMap.class) {
print(i + " tm: " + o);
notfound = false;
}
if (o.getClass() == HashMap.class) {
print(i + " hm: " + o);
notfound = false;
}
if (o.getClass() == LinkedList.class) {
print(i + " ll: " + o);
notfound = false;
}
if (o.getClass() == PriorityQueue.class) {
print(i + " pq : " + o);
notfound = false;
}
if (o.getClass() == pair.class) {
print(i + " pq : " + o);
notfound = false;
}
if (notfound) {
print(i + " unknown: " + o);
}
i++;
}
print("watch ends ");
}
} | Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | b2d4dc7e07e3ca794955aa045109d4d1 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
long rem = 1000000000L;
InputReader sc;
boolean singleTest = true;
ArrayList<Integer>[] adj;
int[] a;
int[] b;
int[] c;
boolean[] visited;
long res;
public void solve(int test){
int n = nextInt();
a = new int[n+1];
b = new int[n+1];
c = new int[n+1];
for(int i=1; i<=n; i++){
a[i] = nextInt();
b[i] = nextInt();
c[i] = nextInt();
}
adj = new ArrayList[n+1];
for(int i=1; i<=n; i++){
adj[i] = new ArrayList<Integer>();
}
visited = new boolean[n+1];
for(int i=1; i<n; i++){
int u = nextInt();
int v = nextInt();
adj[u].add(v);
adj[v].add(u);
}
res = 0L;
Pair p = dfs(1, Integer.MAX_VALUE);
if((p.x > 0) || (p.y > 0)){
println("-1");
}
else{
println(res);
}
}
public Pair dfs(int root, int minC){
minC = Math.min(a[root], minC);
visited[root] = true;
Pair p = new Pair(0, 0);
if(b[root] != c[root]){
p.x += c[root];
p.y += b[root];
}
for(int child : adj[root]){
if(!visited[child]){
Pair temp = dfs(child, minC);
p.x += temp.x;
p.y += temp.y;
}
}
int nodes = Math.min(p.x, p.y);
res += (nodes*(minC*2L));
p.x -= nodes;
p.y -= nodes;
return p;
}
class Pair{
public int x;
public int y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
}
public int[] initialize(int[] arr, int len, int val){
for(int i=0; i<len; i++){
arr[i] = val;
}
return arr;
}
public long[] initialize(long[] arr, int len, long val){
for(int i=0; i<len; i++){
arr[i] = val;
}
return arr;
}
public boolean[] initialize(boolean[] arr, int len, boolean val){
for(int i=0; i<len; i++){
arr[i] = val;
}
return arr;
}
public int[] initialize(int[] arr, int val){
return initialize(arr, arr.length, val);
}
public long[] initialize(long[] arr, long val){
return initialize(arr, arr.length, val);
}
public boolean[] initialize(boolean[] arr, boolean val){
return initialize(arr, arr.length, val);
}
public int nextInt(){
return sc.nextInt();
}
public long nextLong(){
return sc.nextLong();
}
public String next(){
return sc.next();
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextArrInt(int n){
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = nextInt();
}
return arr;
}
public long[] nextArrLong(int n){
long[] arr = new long[n];
for(int i=0; i<n; i++){
arr[i] = nextLong();
}
return arr;
}
public String[] nextArrWord(int n){
String[] arr = new String[n];
for(int i=0; i<n; i++){
arr[i] = next();
}
return arr;
}
public void println(String str){
System.out.println(str);
}
public void println(int num){
System.out.println(num);
}
public void println(long num){
System.out.println(num);
}
public void print(String str){
System.out.print(str);
}
public void print(int num){
System.out.print(num);
}
public void print(long num){
System.out.print(num);
}
public void printArr(int[] arr){
int n = arr.length;
for(int i=0; i<(n-1); i++){
print(arr[i] + " ");
}
println(arr[n-1]);
}
public void printArr(int[] arr, int n){
print(n+" ");
for(int i=0; i<(n-1); i++){
print(arr[i] + " ");
}
println(arr[n-1]);
}
public void printArr(long[] arr){
int n = arr.length;
for(int i=0; i<(n-1); i++){
print(arr[i] + " ");
}
println(arr[n-1]);
}
public void printArr(long[] arr, int n){
print(n+" ");
for(int i=0; i<(n-1); i++){
print(arr[i] + " ");
}
println(arr[n-1]);
}
public Solution(){
sc = new InputReader();
int tests = 1;
if(!singleTest){
tests = sc.nextInt();
}
for(int t=1; t<=tests; t++){
solve(t);
}
}
public static void main(String[] args){
new Solution();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(){
InputStream stream = System.in;
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next(){
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(IOException e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public String nextLine(){
try{
return reader.readLine();
}catch(IOException e){
throw new RuntimeException(e);
}
}
} | Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | dc95185125a97e3ebd2b000429161654 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
long mod=998244353L;
int[][] dir=new int[][] {{0,1},{1,0},{0,-1},{-1,0}};
long inf=Long.MAX_VALUE;
long gcd(long a,long b) {
return a==0?b:gcd(b%a,a);
}
long[][] A;
long cost;
ArrayList<Integer>[] graph;
void work() {
int n=ni();
A=new long[n][];
for(int i=0;i<n;i++) {
A[i]=na(3);
}
graph=ng(n,n-1);
int c=dfs(0,Long.MAX_VALUE,new boolean[n]);
if(c!=0) {
out.println(-1);
}else {
out.println(cost);
}
}
private int dfs(int node, long v, boolean[] vis) {
vis[node]=true;
v=Math.min(v, A[node][0]);
int c=(int)(A[node][2]-A[node][1]),c1=0,c2=0;
if(c>0) {
c1++;
}else if(c<0) {
c2++;
}
for(int nn:graph[node]) {
if(!vis[nn]) {
int r=dfs(nn,v,vis);
if(r>0) {
c1+=r;
}else {
c2-=r;
}
}
}
cost+=Math.min(c1, c2)*v*2;
return c1-c2;
}
private long pow(long v, long k) {
long ret=1;
while(k>0) {
if(k%2==1) {
ret=(ret*v)%mod;
}
k/=2;
v=(v*v)%mod;
}
return ret;
}
//input
private ArrayList<Integer>[] ng(int n, int m) {
ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
int s=in.nextInt()-1,e=in.nextInt()-1;
graph[s].add(e);
graph[e].add(s);
}
return graph;
}
private ArrayList<long[]>[] ngw(int n, int m) {
ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
graph[(int)s].add(new long[] {e,w,i});
graph[(int)e].add(new long[] {s,w});
}
return graph;
}
private int ni() {
return in.nextInt();
}
private long nl() {
return in.nextLong();
}
private String ns() {
return in.next();
}
private long[] na(int n) {
long[] A=new long[n];
for(int i=0;i<n;i++) {
A[i]=in.nextLong();
}
return A;
}
private int[] nia(int n) {
int[] A=new int[n];
for(int i=0;i<n;i++) {
A[i]=in.nextInt();
}
return A;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
while(st==null || !st.hasMoreElements())//回车,空行情况
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 1636ac628f2f005202fe517d5aba06a8 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
int[] cnt0;
int[] cnt1;
int[] c;
LinkedList<Integer> adj[];
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt();
adj = new LinkedList[n];
c = new int[n]; cnt0 = new int[n]; cnt1 = new int[n];
for(int i = 0; i < n; i++) {
adj[i] = new LinkedList<>();
c[i] = f.nextInt();
int a = f.nextInt(), b = f.nextInt();
if(a == 0 && b == 1) cnt0[i]++;
else if(b == 0 && a == 1) cnt1[i]++;
}
for(int i = 0; i < n-1; i++) {
int a = f.nextInt()-1, b = f.nextInt()-1;
adj[a].add(b);
adj[b].add(a);
}
long ans = dfs(0, -1, Long.MAX_VALUE);
if(cnt0[0] + cnt1[0] != 0) out.println(-1);
else out.println(2*ans);
out.flush();
}
public long dfs(int i, int p, long cost) {
cost = Math.min(cost, c[i]);
long ans = 0;
for(int j : adj[i])
if(j != p) {
ans += dfs(j,i,cost);
cnt0[i] += cnt0[j];
cnt1[i] += cnt1[j];
}
long min = Math.min(cnt0[i], cnt1[i]);
cnt0[i] -= min; cnt1[i] -= min;
return ans + cost*min;
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | b9dd38fd332f37ac686002542becc4b7 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class Problem_E {
static final long INF = Long.MAX_VALUE / 2;
static List<Integer>[] G;
static long[] A, dp;
static int[] B, C;
public static void dfs(int x, int p) {
for (int y : G[x]) {
if (y == p) {
continue;
}
A[y] = Math.min(A[x], A[y]);
dfs(y, x);
B[x] += B[y];
C[x] += C[y];
}
int min = Math.min(B[x], C[x]);
B[x] -= min;
C[x] -= min;
dp[x] = 2 * A[x] * min;
for (int y : G[x]) {
if (y == p) {
continue;
}
dp[x] += dp[y];
}
}
public static void main(String[] args) {
InputReader in = new InputReader();
int N = in.nextInt();
A = new long[N + 1];
B = new int[N + 1];
C = new int[N + 1];
for (int i = 1; i <= N; i++) {
A[i] = in.nextInt();
B[i] = in.nextInt();
C[i] = in.nextInt();
if (B[i] == C[i]) {
B[i] = C[i] = 0;
}
}
G = new List[N + 1];
for (int i = 1; i <= N; i++) {
G[i] = new ArrayList<>();
}
for (int i = 1; i < N; i++) {
int u = in.nextInt();
int v = in.nextInt();
G[u].add(v);
G[v].add(u);
}
dp = new long[N + 1];
dfs(1, -1);
System.out.println(B[1] == C[1] ? dp[1] : -1);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer st;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 62a749b306073521a060e9535894eada | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class Problem_E {
static final long INF = Long.MAX_VALUE / 2;
static List<Integer>[] G;
static long[] A, dp;
static int[] B, C, D, E;
public static void dfs(int x, int p) {
dp[x] = B[x] == C[x] ? 0 : A[x];
for (int y : G[x]) {
if (y == p) {
continue;
}
A[y] = Math.min(A[x], A[y]);
dfs(y, x);
D[x] += D[y];
E[x] += E[y];
}
int min = Math.min(D[x], E[x]);
D[x] -= min;
E[x] -= min;
dp[x] = 2 * A[x] * min;
for (int y : G[x]) {
if (y == p) {
continue;
}
dp[x] += dp[y];
}
}
public static void main(String[] args) {
InputReader in = new InputReader();
int N = in.nextInt();
A = new long[N + 1];
B = new int[N + 1];
C = new int[N + 1];
D = new int[N + 1]; // not necessary zero
E = new int[N + 1]; // not necessary one
for (int i = 1; i <= N; i++) {
A[i] = in.nextInt();
B[i] = in.nextInt();
C[i] = in.nextInt();
if (B[i] == C[i]) {
continue;
}
if (B[i] == 0) {
D[i]++;
} else {
E[i]++;
}
}
G = new List[N + 1];
for (int i = 1; i <= N; i++) {
G[i] = new ArrayList<>();
}
for (int i = 1; i < N; i++) {
int u = in.nextInt();
int v = in.nextInt();
G[u].add(v);
G[v].add(u);
}
dp = new long[N + 1];
dfs(1, -1);
System.out.println(D[1] == E[1] ? dp[1] : -1);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer st;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 29a8ce146d28e1f3f320d2425ac1733c | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | //package codeforces;
import java.io.*;
import java.util.*;
public class TreeShuffling {
int V;
static LinkedList <Integer> ar[];
static long arr[];
static int a[];
static int b[];
static long cost=0;
public TreeShuffling(int v) {
ar=new LinkedList[v];
for(int i=0;i<v;i++) {
ar[i]=new LinkedList<>();
}
}
static int[] dfs(int u,boolean visited[],long min) {
int tp[]=new int[2];
if(a[u]!=b[u]) {
if(a[u]==1)
tp[1]+=1;
else
tp[0]+=1;
}
visited[u]=true;
for(int node : ar[u]) {
if(!visited[node]) {
int df[]=dfs(node,visited,Math.min(min, arr[u]));
tp[0]+=df[0];
tp[1]+=df[1];
}
}
if(arr[u]<min) {
int val=Math.min(tp[0], tp[1]);
cost+=2*val*arr[u];
tp[0]-=val;
tp[1]-=val;
}
return tp;
}
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 fr=new FastReader();
int n=fr.nextInt();
TreeShuffling tr=new TreeShuffling(n);
arr=new long[n];
a=new int[n];
b=new int[n];
for(int i=0;i<n;i++) {
arr[i]=fr.nextLong();
a[i]=fr.nextInt();
b[i]=fr.nextInt();
}
for(int i=0;i<n-1;i++) {
int u=fr.nextInt();
int v=fr.nextInt();
ar[u-1].add(v-1);
ar[v-1].add(u-1);
}
boolean visited[]=new boolean[n];
Arrays.fill(visited,false);
int ans[]=dfs(0,visited,(long)Math.pow(10,18));
if(ans[0]>0 || ans[1]>0)
System.out.println("-1");
else
System.out.println(cost);
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 3abff48627cd73ac123f7eb1ce4c6876 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.util.*;
public class Main {
final static int maxn=(int)2e5+10;
static int a[]=new int [maxn];
static int b[]=new int [maxn];
static int c[]=new int [maxn];
static Vector<Integer>vec[]=new Vector[maxn];
static long cost=(int)1e9+10;
static int num1[]=new int [maxn];
static int num0[]=new int [maxn];
static long ans=0;
static void dfs(int u,int pre)
{
if(pre!=0)
{
a[u]=Math.min(a[u], a[pre]);
}
for(int i=0;i<vec[u].size();i++)
{
int v=vec[u].get(i);
if(v==pre)continue;
dfs(v,u);
num0[u]+=num0[v];
num1[u]+=num1[v];
}
if(b[u]!=c[u])
{
if(b[u]==1)num1[u]++;
else
num0[u]++;
}
int minnum=Math.min(num0[u],num1[u] );
ans+=(long)minnum*a[u]*2;
num0[u]-=minnum;num1[u]-=minnum;
}
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=1;i<=n;i++)vec[i]=new Vector();
int numleft=0;int numright=0;
for(int i=1;i<=n;i++)
{
num1[i]=0;num0[i]=0;
}
for(int i=1;i<=n;i++)
{
a[i]=input.nextInt();b[i]=input.nextInt();c[i]=input.nextInt();
if(b[i]==1)numleft++;
if(c[i]==1)numright++;
}
for(int i=1;i<=n-1;i++)
{
int x,y;x=input.nextInt();y=input.nextInt();
vec[x].add(y);vec[y].add(x);
}
if(numleft!=numright)
{
System.out.println(-1);
}
else
{
dfs(1,0);System.out.println(ans);
}
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 92a47388e287060b170930e7db73bbad | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.*;
import java.util.*;
public class E1 {
public static HashMap<Integer, node> map;
public static HashMap<node, HashSet<node>> tree;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true);
int n = Integer.parseInt(br.readLine());
tree = new HashMap<>();
map = new HashMap<>();
for (int i = 1; i <= n; ++i) {
String array[] = br.readLine().split(" ");
int a = Integer.parseInt(array[0]);
int b = Integer.parseInt(array[1]);
int c = Integer.parseInt(array[2]);
node node = new node(i, b, !(b == c), a);
map.put(i, node);
tree.put(node, new HashSet<>());
}
for (int i = 0; i < n - 1; ++i) {
String array[] = br.readLine().split(" ");
int u = Integer.parseInt(array[0]);
int v = Integer.parseInt(array[1]);
tree.get(map.get(u)).add(map.get(v));
tree.get(map.get(v)).add(map.get(u));
}
long ans = dfs(1, new HashSet<Integer>(), map.get(1).cost);
if(map.get(1).ozl == 0 && map.get(1).zol == 0){
System.out.println(ans*2);
} else {
System.out.println(-1);
}
}
private static long dfs(int node, HashSet<Integer> visited, long min_val) {
visited.add(node);
map.get(node).min = min_val;
long ans = 0;
int oz = 0;
int zo = 0;
for (node child : tree.get(map.get(node))) {
if (visited.contains(child.id))
continue;
ans += dfs(child.id, visited, Math.min(min_val, child.cost));
oz += child.ozl;
zo += child.zol;
}
if (map.get(node).change) {
if (map.get(node).val == 1)
oz++;
else
zo++;
}
int mini = Math.min(oz, zo);
ans += mini*min_val;
oz -= mini;
zo -= mini;
map.get(node).ozl = oz;
map.get(node).zol = zo;
return ans;
}
}
class node {
int id;
int val;
boolean change;
long cost;
long min;
int ozl;
int zol;
node(int id, int val, boolean change, long cost) {
this.id = id;
this.val = val;
this.change = change;
this.cost = cost;
}
} | Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | e6da0c9cd68c91818bc8c18f246e1c36 | train_002.jsonl | 1590935700 | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.IntStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Optional;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author out_of_the_box
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ETreeShuffling solver = new ETreeShuffling();
solver.solve(1, in, out);
out.close();
}
static class ETreeShuffling {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
int[] c = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
b[i] = in.nextInt();
c[i] = in.nextInt();
}
int fv = 0;
int sv = 0;
for (int i = 0; i < n; i++) {
if (b[i] == 1) fv++;
if (c[i] == 1) sv++;
}
if (fv != sv) {
out.println(-1);
return;
}
Graph<Integer, Graph.BaseEdge<Integer>> graph = new AdjacencyList<>();
for (int i = 0; i < n; i++) {
graph.addVertex(i);
}
for (int i = 0; i < (n - 1); i++) {
int u = in.nextInt();
u--;
int v = in.nextInt();
v--;
Graph.BaseEdge<Integer> edge = Graph.BaseEdge.of(u, v);
graph.addEdge(edge);
}
Queue<Integer> q = new LinkedList<>();
q.add(0);
int[] par = new int[n];
par[0] = 0;
int[] rank = new int[n];
rank[0] = 0;
while (!q.isEmpty()) {
int u = q.poll();
List<Integer> seconds = graph.getEdges(u).stream().map(e -> e.second).collect(Collectors.toList());
for (int v : seconds) {
if (v != par[u]) {
par[v] = u;
a[v] = Math.min(a[v], a[u]);
q.add(v);
rank[v] = rank[u] + 1;
}
}
}
int[] bottomOrder = IntStream.range(0, n).boxed().sorted(Comparator.comparingInt(i -> -rank[i]))
.mapToInt(i -> i).toArray();
int[] r = new int[n];
int[] s = new int[n];
for (int i = 0; i < n; i++) {
if (b[i] != c[i]) {
if (b[i] == 0) {
s[i]++;
} else {
r[i]++;
}
}
}
for (int i = 0; i < n; i++) {
int u = bottomOrder[i];
if (u != par[u]) {
r[par[u]] += r[u];
s[par[u]] += s[u];
}
}
long ans = 0L;
long[] tans = new long[n];
for (int i = 0; i < n; i++) {
tans[i] = ((long) Math.min(r[i], s[i])) * ((long) a[i]);
}
for (int i = 0; i < n; i++) {
int u = bottomOrder[i];
if (u != par[u]) {
tans[par[u]] -= ((long) Math.min(r[u], s[u])) * ((long) a[par[u]]);
}
}
for (int i = 0; i < n; i++) {
ans += tans[i];
}
ans <<= 1L;
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface Graph<V, E extends Graph.Edge<V, E>> {
Graph<V, E> addVertex(V v);
Graph<V, E> addEdge(E e);
List<E> getEdges(V vertex);
abstract class Edge<V, E extends Graph.Edge<V, E>> {
public V first;
public V second;
public Edge(V first, V second) {
this.first = first;
this.second = second;
}
public abstract E reverse();
}
class BaseEdge<V> extends Graph.Edge<V, Graph.BaseEdge<V>> {
private BaseEdge(V first, V second) {
super(first, second);
}
public static <A> Graph.BaseEdge<A> of(A fir, A sec) {
return new Graph.BaseEdge<>(fir, sec);
}
public Graph.BaseEdge<V> reverse() {
return Graph.BaseEdge.of(second, first);
}
}
}
static class AdjacencyList<V, E extends Graph.Edge<V, E>> implements Graph<V, E> {
public Map<V, List<E>> adjList;
private Map<E, E> reverseMap;
public boolean directed;
public AdjacencyList() {
this.adjList = new HashMap<>();
this.directed = false;
this.reverseMap = new HashMap<>();
}
public AdjacencyList(boolean directed) {
this.adjList = new HashMap<>();
this.directed = directed;
this.reverseMap = new HashMap<>();
}
public List<E> getEdges(V vertex) {
return Optional.ofNullable(adjList.get(vertex)).orElseGet(ArrayList::new);
}
public Graph<V, E> addVertex(V v) {
List<E> edges = Optional.ofNullable(adjList.get(v)).orElseGet(ArrayList::new);
adjList.put(v, edges);
return this;
}
public Graph<V, E> addEdge(E e) {
V v1 = e.first;
V v2 = e.second;
List<E> edges1 = Optional.ofNullable(adjList.get(v1)).orElseGet(ArrayList::new);
edges1.add(e);
adjList.put(v1, edges1);
if (!directed) {
E reverseEdge = e.reverse();
List<E> edges2 = Optional.ofNullable(adjList.get(v2)).orElseGet(ArrayList::new);
edges2.add(reverseEdge);
adjList.put(v2, edges2);
reverseMap.put(e, reverseEdge);
reverseMap.put(reverseEdge, e);
}
return this;
}
}
}
| Java | ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"] | 2 seconds | ["4", "24000", "-1"] | NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | 4dce15ff1446b5af2c5b49ee2d30bbb8 | First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. | 2,000 | Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. | standard output | |
PASSED | 678bf7445e3ccfa23e287a7cb5dbf73e | train_002.jsonl | 1366040100 | This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) — bus, (2) — ring, (3) — star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
OutputStream out = new BufferedOutputStream ( System.out );
//try {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<TreeSet<Integer>> paths = new ArrayList<TreeSet<Integer>>();
//int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++) {
paths.add(new TreeSet<Integer>());
}
for(int i = 0; i < m; i++) {
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
paths.get(a).add(b);
paths.get(b).add(a);
// matrix[a][b] = 1;
// matrix[b][a] = 1;
}
int[] counts = new int[3];
for(int i = 0; i < n; i++) {
int size = paths.get(i).size();
if(size <= 2)
counts[size]++;
}
if(counts[1] == 2 && counts[2] == n-2) {
System.out.println("bus topology");
}
else if(counts[2] == n) {
System.out.println("ring topology");
}
else if(counts[1] == n-1) {
System.out.println("star topology");
} else {
System.out.println("unknown topology");
}
// for(int i = 0; i < n; i++) {
// System.out.println(paths.get(i).toString());
// out.write((paths.get(i).toString() + "\n").getBytes());
// minRecog(i, i, i, paths, 0, 0, stack);
// }
// for(int i = 0; i < n; i++) {
// System.out.println(Arrays.toString(matrix[i]));
// out.write((paths.get(i).toString() + "\n").getBytes());
// minRecog(i, i, i, paths, 0, 0, stack);
// }
//} catch(IOException ex) {}
}
}
| Java | ["4 3\n1 2\n2 3\n3 4", "4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n1 2\n1 3\n1 4", "4 4\n1 2\n2 3\n3 1\n1 4"] | 2 seconds | ["bus topology", "ring topology", "star topology", "unknown topology"] | null | Java 8 | standard input | [
"implementation",
"graphs"
] | 7bb088ce5e4e2101221c706ff87841e4 | The first line contains two space-separated integers n and m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. | 1,200 | In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). | standard output | |
PASSED | d9e883ef198916a0da5d1cb8fb45c266 | train_002.jsonl | 1366040100 | This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) — bus, (2) — ring, (3) — star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. | 256 megabytes | import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collections;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
Graph g;
public void solve(int testNumber, InputReader in, PrintWriter out) {
g = new Graph();
int n = in.nextInt();
int m = in.nextInt();
g.initGraph(n, m);
int[] deg = new int[n];
for (int i = 0; i < m; ++i) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;g.addEdge(a, b);
++deg[a];
++deg[b];
}
boolean[] u = new boolean[n];
dfs(0, g, u);
for (int i = 0; i < n; ++i) {
if (!u[i]) {
out.println("unknown topology");
return;
}
}
int amOnes = 0;
int amTwos = 0;
int amN = 0;
for (int i = 0; i < n; ++i) {
if (deg[i] == 1) ++amOnes;
if (deg[i] == 2) ++amTwos;
if (deg[i] == n-1) ++amN;
}
if (amN == 1 && amOnes == n-1) {
out.println("star topology");
} else if (amTwos == n) {
out.println("ring topology");
} else if (amOnes == 2 && amTwos == n-2) {
out.println("bus topology");
} else {
out.println("unknown topology");
}
}
private void dfs(int v, Graph g, boolean[] u) {
u[v] = true;
for (int e = g.first[v]; e != -1; e = g.next[e]) {
int to = g.to[e];
if (!u[to]) {
dfs(to, g, u);
}
}
}
}
class Graph {
public int[] from;
public int[] to;
public int[] first;
public int[] next;
public int nVertex;
public int nEdges;
public int curEdge;
public Graph() {}
public void initGraph(int n, int m) {
curEdge = 0;
nVertex = n;
nEdges = m;
from = new int[m * 2];
to = new int[m * 2];
first = new int[n];
next = new int[m * 2];
Arrays.fill(first, -1);
}
public void addEdge(int a, int b) {
next[curEdge] = first[a];
first[a] = curEdge;
to[curEdge] = b;
from[curEdge] = a;
++curEdge;
next[curEdge] = first[b];
first[b] = curEdge;
to[curEdge] = a;
from[curEdge] = b;
++curEdge;
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
| Java | ["4 3\n1 2\n2 3\n3 4", "4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n1 2\n1 3\n1 4", "4 4\n1 2\n2 3\n3 1\n1 4"] | 2 seconds | ["bus topology", "ring topology", "star topology", "unknown topology"] | null | Java 8 | standard input | [
"implementation",
"graphs"
] | 7bb088ce5e4e2101221c706ff87841e4 | The first line contains two space-separated integers n and m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. | 1,200 | In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.