exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
β | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
β | difficulty
int64 -1
3.5k
β | prob_desc_output_spec
stringlengths 17
1.47k
β | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 3bc2dbbeda33c8420c3b42af54fcb074 | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sparsh Sanchorawala
*/
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);
FChips solver = new FChips();
solver.solve(1, in, out);
out.close();
}
static class FChips {
public void solve(int testNumber, InputReader s, PrintWriter w) {
int n = s.nextInt(), k = s.nextInt();
String str = s.next();
int[] a = new int[n];
for (int i = 0; i < n; i++)
if (str.charAt(i) == 'B')
a[i] = 1;
Queue<Integer> q = new LinkedList<>();
int[] color = new int[n];
Arrays.fill(color, -1);
int[] level = new int[n];
Arrays.fill(level, -1);
for (int i = 0; i < n; i++) {
if (a[(i - 1 + n) % n] == a[i] || a[(i + 1) % n] == a[i]) {
q.add(i);
color[i] = a[i];
level[i] = 0;
}
}
while (!q.isEmpty()) {
int x = q.poll();
if (level[x] == k)
break;
if (level[(x - 1 + n) % n] == -1) {
q.add((x - 1 + n) % n);
color[(x - 1 + n) % n] = color[x];
level[(x - 1 + n) % n] = level[x] + 1;
}
if (level[(x + 1) % n] == -1) {
q.add((x + 1) % n);
color[(x + 1) % n] = color[x];
level[(x + 1) % n] = level[x] + 1;
}
}
for (int i = 0; i < n; i++) {
if (color[i] != -1) {
if (color[i] == 0)
w.print("W");
else
w.print("B");
} else {
if ((a[i] + k) % 2 == 0)
w.print("W");
else
w.print("B");
}
}
w.println();
}
}
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 String nextString() {
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 nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | 8bc37ba34f992d515fc90dcf177c081c | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes | import java.io.*;
import java.util.*;
public class F implements Runnable {
public static void main (String[] args) {new Thread(null, new F(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
int n = fs.nextInt();
int k = fs.nextInt();
char[] str = fs.next().toCharArray();
boolean checker = true;
for(int i = 0; i < n; i++) {
int prev = (i-1+n)%n;
int next = (i+1)%n;
checker &= str[prev] == str[next] && str[prev] != str[i];
}
if(checker) {
k &= 1;
for(int i = 0; i < n; i++) {
if(k > 0) {
if(str[i] == 'W') str[i] = 'B';
else str[i] = 'W';
}
}
out.println(new String(str));
out.close();
return;
}
ArrayList<Range> list = new ArrayList<>();
boolean[] vis = new boolean[n];
for(int i = 0; i < n; i++) {
if(vis[i]) continue;
if(str[(i-1+n)%n] == str[i] || str[(i+1)%n] == str[i]) continue;
int j = (i-1+n)%n;
while(!vis[j]) {
vis[j] = true;
int prev = j-1; if(prev < 0) prev += n;
int next = j+1; if(next >= n) next -= n;
if(str[prev] == str[next] && str[next] != str[j]) {
j = prev;
}
else {
j = next;
break;
}
}
int j2 = (i+1)%n;
while(!vis[j2]) {
vis[j2] = true;
int prev = j2-1; if(prev < 0) prev += n;
int next = j2+1; if(next >= n) next -= n;
if(str[prev] == str[next] && str[next] != str[j2]) {
j2 = next;
}
else {
j2 = prev;
break;
}
}
Range add = new Range(j, j2);
add.setLen(n);
list.add(add);
}
Collections.sort(list);
while(!list.isEmpty() && k > 0) {
// for(Range r : list) System.out.println(r + " " + r.len);
// System.out.println();
k--;
for(int i = 0; i < list.size(); i++) {
Range now = list.get(i);
int sub = 1;
if(now.start != now.end) sub++;
if(now.flips == 0) {
str[now.start] = flip(str[now.start]);
if(now.start != now.end) {
str[now.end] = flip(str[now.end]);
}
}
now.len -= sub;
now.flips ^= 1;
now.start++; if(now.start >= n) now.start -= n;
now.end--; if(now.end < 0) now.end += n;
}
while(!list.isEmpty() && list.get(list.size()-1).len <= 0) {
list.remove(list.size()-1);
}
}
for(Range r : list) {
if(r.flips != 0) {
if(r.start == r.end) str[r.start] = flip(str[r.start]);
else {
for(int i = r.start; i != r.end; i = (i+1)%n) {
str[i] = flip(str[i]);
}
str[r.end] = flip(str[r.end]);
}
}
}
out.println(new String(str));
out.close();
}
char flip(char a) {
if(a == 'W') return 'B';
return 'W';
}
class Range implements Comparable<Range> {
int start, end, len, flips = 0;
Range(int s, int e) {
start = s; end = e;
}
void setLen(int n) {
if(start <= end) {
len = end-start+1;
}
else {
len = n-start;
len += end+1;
}
}
public int compareTo(Range r) {
return Integer.compare(r.len, len);
}
public String toString() {
return String.format("(%d, %d)", start, end);
}
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | 7bfa06b5d9941ac1bb4bb99ea062b787 | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes |
/**
* @author Juan Sebastian Beltran Rojas
* @mail [email protected]
* @veredict
* @url https://codeforces.com/problemset/problem/1244/F
* @category implementation
* @date 18/10/2019
**/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Integer.parseInt;
public class CF1244F {
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String ln; (ln = in.readLine()) != null; ) {
StringTokenizer st = new StringTokenizer(ln);
int N = parseInt(st.nextToken()), K = parseInt(st.nextToken());
char[] S = in.readLine().toCharArray();
N=S.length;
char[] s = new char[2*N];
for(int i=0;i<N;i++)
s[i]=s[N+i]=S[i];
if (f(s, N)) {
if (K % 2 == 1)
s = move(s, N);
} else {
for (; K > 0; K--) {
ArrayList<int[]> list = get(s, N);
if(list.size()==0)break;
int max = 0;
for(int[] l:list)
max = Math.max(max, (l[1]-l[0])/2);
max = Math.min(max, K);
s = move(s, N, max, list);
K-=max;
}
}
System.out.println(Arrays.copyOf(s, N));
}
}
static ArrayList<int[]> get(char[] S, int N) {
int ant = -1;
ArrayList<int[]> list = new ArrayList<>();
for(int i=0;i<2*N-1;i++)
if(S[i]==S[i+1]) {
if(ant!=-1&&i-ant>1&&ant<N) {
list.add(new int[]{ant, i});
if(i>=N&&list.size()>0&&list.get(0)[0]==0)
list.remove(0);
}
ant = -1;
}
else if(ant == -1)
ant = i;
return list;
}
static char[] move(char[] s, int N, int C, ArrayList<int[]> list) {
for(int[] l:list) {
int i=l[0]+1, c=0, j=l[1]-1;
for(;c<C&&i<=j;c++,i++,j--) {
s[i] = s[i<N?i+N:i%N] = s[l[0]];
s[j] = s[j<N?j+N:j%N] = s[l[1]];
}
for(;i<=j;i++)
s[i] = s[i<N?i+N:i%N] = s[i-1]=='W'?'B':'W';
}
return s;
}
static char[] move(char[] s, int N) {
char[] n = new char[s.length];
for (int i = 0; i < N; i++) {
int W = (s[i] == 'W' ? 1 : 0) + (s[i == 0 ? N - 1 : i - 1] == 'W' ? 1 : 0) + (s[(i + 1) % N] == 'W' ? 1 : 0);
if (W >= 2) n[i] = n[N+i] = 'W';
else n[i] = n[N+i] = 'B';
}
return n;
}
static boolean f(char[] s, int N) {
for (int i = 0; i < N - 1; i++)
if (s[i] == s[i + 1])
return false;
return s[0] != s[N - 1];
}
}
| Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | fc10f9843b0ecae5dd045d083395a7db | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes | import java.util.*;
import java.io.*;
public class Chips {
static BufferedReader br;
static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
int k = nextInt();
boolean[] white = new boolean[n];
{
String str = next();
for(int i = 0; i < n; i++) {
white[i] = str.charAt(i) == 'W';
}
}
ArrayList<Integer> shift = new ArrayList<Integer>();
if(white[n - 1] == white[1] && white[1] != white[0])
shift.add(0);
for(int i = 1; i < n - 1; i++)
if(white[i - 1] == white[i + 1] && white[i - 1] != white[i])
shift.add(i);
if(white[n - 2] == white[0] && white[0] != white[n - 1])
shift.add(n - 1);
if(shift.size() == n) {
StringBuilder sb = new StringBuilder();
boolean flip = ((k & 1) == 1);
for(boolean b: white)
if(flip) sb.append(b ? 'B':'W');
else sb.append(b ? 'W' : 'B');
System.out.println(sb);
return;
}
int x = -1;
if(shift.size() > 1 && shift.get(0) == 0 && shift.get(shift.size() - 1) == n - 1) {
ArrayList<Integer> t1 = new ArrayList<Integer>();
boolean[] temp = new boolean[n];
x = 0;
for(int i = shift.size() - 2; i >= 0; i--) {
if(shift.get(i) != shift.get(i + 1) - 1) {
x = i + 1;
break;
}
}
for(int i = x; i < shift.size(); i++)
t1.add(i - x);
for(int i = 0; i < x; i++)
t1.add(shift.get(i) + shift.size() - x);
x = shift.get(x);
for(int i = x; i < n; i++)
temp[i - x] = white[i];
for(int i = 0; i < x; i++)
temp[n - x + i] = white[i];
white = temp;
shift = t1;
}
{
int s = 0;
int e = 1;
while(s < shift.size()) {
while(e < shift.size() && shift.get(e) - 1 == shift.get(e - 1) && white[shift.get(e - 1)] != white[shift.get(e)])
e++;
if(e != s + 1) {
int m = (s + e) / 2 - 1;
int m1 = e - (e - s) / 2;
for(int i = s; i < m + 1; i++) {
if(i < k + s)
white[shift.get(i)] = white[Math.floorMod((shift.get(s) - 1), n)];
else
white[shift.get(i)] = ((k & 1) == 1 ? !white[shift.get(i)]: white[shift.get(i)]);
}
for(int i = e - 1; i >= m1; i--) {
if(i >= e - k)
white[shift.get(i)] = white[(shift.get(e - 1) + 1) % n];
else
white[shift.get(i)] = ((k & 1) == 1 ? !white[shift.get(i)]: white[shift.get(i)]);
}
if(k > m - s + 1 && m1 - m == 2 && white[Math.floorMod((shift.get(s) - 1), n)] == white[(shift.get(e - 1) + 1) % n] && ((k & 1) == 1 ? !white[shift.get(m) + 1] : white[shift.get(m) + 1]) != white[(shift.get(e - 1) + 1) % n])
white[shift.get(m) + 1] = white[(shift.get(e - 1) + 1) % n];
else if(m1 - m == 2)
white[shift.get(m) + 1] = ((k & 1) == 1 ? !white[shift.get(m) + 1] : white[shift.get(m) + 1]);
}
else
white[shift.get(s)] = white[(shift.get(s) + 1) % n];
s = e;
e++;
}
}
StringBuilder sb = new StringBuilder();
if(x == -1)
for(int i = 0; i < n; i++)
sb.append(white[i] ? 'W' : 'B');
else {
for(int i = n - x; i < n; i++)
sb.append(white[i] ? 'W' : 'B');
for(int i = 0; i < n - x; i++)
sb.append(white[i] ? 'W' : 'B');
}
System.out.println(sb);
}
public static String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
| Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | 0c5b6a6f3699a4b1ebc1ef70377ee2df | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
String s = br.readLine();
int[] A = new int[n];
for(int i = 0; i < n; i++) if(s.charAt(i) == 'W') A[i] = 1;
int[] final_color = new int[n];
Queue<Integer> queue = new LinkedList<Integer>();
int[] turbulence = new int[n];
Arrays.fill(turbulence, -1);
Arrays.fill(final_color, -1);
for(int i = 0; i < n; i++)
{
if(A[(i-1+n)%n] == A[i] || A[(i+1)%n] == A[i])
{
turbulence[i] = 0;
final_color[i] = A[i];
queue.add(i);
}
}
while(queue.size() != 0)
{
int x = queue.poll();
if(turbulence[x] == k) break;
if(final_color[(x-1+n)%n] == -1)
{
queue.add((x-1+n)%n);
turbulence[(x-1+n)%n] = turbulence[x]+1;
final_color[(x-1+n)%n] = final_color[x];
}
if(final_color[(x+1)%n] == -1)
{
queue.add((x+1)%n);
turbulence[(x+1)%n] = turbulence[x]+1;
final_color[(x+1)%n] = final_color[x];
}
}
for(int i = 0; i < n; i++)
{
if(final_color[i] == 0) System.out.print("B");
else if(final_color[i] == 1) System.out.print("W");
else
{
if(A[(i+k)%2] == 1) System.out.print("W");
else System.out.print("B");
}
}
}
}
| Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | 85655cbb303e9b1a9820cc0dfdc1be58 | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long M = 1000000007;
StringBuffer sb = new StringBuffer();
void solve() {
int n = ni();
long K = nl();
String s = ns();
char[] a = (s + s).toCharArray();
n = a.length / 2;
List<int[]> ls = new ArrayList<int[]>();
for (int i = 0; i < n;) {
// tr(i, a[i]);
int r = i + 1;
for (; r < a.length && a[r] != a[r - 1]; r++)
;
if (i <= r - 2) {
ls.add(new int[] { i, r - 2 });
}
for (; r < a.length && a[r] == a[r - 1]; r++)
;
i = r;
}
// for (int[] l : ls)
// tr(l);
if (!ls.isEmpty()) {
int[] last = ls.get(ls.size() - 1);
if (last[1] - last[0] > n) {
if (K % 2 == 0)
sb.append(s);
else
sb.append(s.substring(1)).append(s.charAt(0));
return;
} else if (last[1] < n) {
if (ls.get(0)[0] == 0 && s.charAt(0) == s.charAt(n - 1))
ls.get(0)[0]++;
} else
ls.remove(0);
for (int[] l : ls) {
// bbwbwbwbb
int i = l[0];
for (; i <= (l[0] + l[1]) / 2; i++) {
int d = i - l[0] + 1;
if (d <= K)
a[i % n] = a[(l[0] - 1 + n) % n];
else
a[i % n] = rev(a[i % n], K);
}
for (; i <= l[1]; i++) {
int d = -i + l[1] + 1;
if (d <= K)
a[i % n] = a[l[1] + 1];
else
a[i % n] = rev(a[i], K);
}
}
for (int i = 0; i < n; i++)
sb.append(a[i]);
} else
sb.append(s);
// sb.append(m.lastKey() - m.firstKey());
}
private char rev(char c, long k) {
if (k % 2 == 1)
c = (c == 'B' ? 'W' : 'B');
return c;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.println(sb);
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(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[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
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 static void tr(Object... o) {
System.err.println(Arrays.deepToString(o));
System.err.flush();
}
} | Java | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | fb31599f776d2a173bd9f816e2b76c16 | train_000.jsonl | 1570957500 | There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations. | 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(){
out.println(work());
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
String work() {
int n=in.nextInt();
long k=in.nextLong();
String str=in.next();
boolean f=false;
char[] ret=new char[n];
int s=0;
for(int i=0;i<n;i++) {
if(str.charAt(i)==str.charAt(i==0?n-1:i-1)) {
f=true;
s=i;
break;
}
}
if(!f) {
for(int i=0;i<n;i++) {
if((k%2==0&&str.charAt(i)=='B')||(k%2==1&&str.charAt(i)=='W')) {
ret[i]='B';
}else {
ret[i]='W';
}
}
return new String(ret);
}
int[] rec=new int[n];
for(int i=s;;) {
if(str.charAt(i)!=str.charAt(i==n-1?0:i+1)&&str.charAt(i)!=str.charAt(i==0?n-1:i-1)) {
rec[i]=rec[i==0?n-1:i-1]+1;
}
i++;
if(i==n)i=0;
if(i==s)break;
}
for(int i=s;;) {
int v=0;
if(str.charAt(i)!=str.charAt(i==n-1?0:i+1)&&str.charAt(i)!=str.charAt(i==0?n-1:i-1)) {
v=rec[i==n-1?0:i+1]+1;
}
rec[i]=Math.min(rec[i], v);
i--;
if(i==-1)i=n-1;
if(i==s)break;
}
for(int i=0;i<n;i++) {
if(rec[i]<=k) {
if(rec[i]%2==0) {
ret[i]=str.charAt(i);
}else {
ret[i]=str.charAt(i)=='W'?'B':'W';
}
}else {
if(k%2==0) {
ret[i]=str.charAt(i);
}else {
ret[i]=str.charAt(i)=='W'?'B':'W';
}
}
}
return new String(ret);
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(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 | ["6 1\nBWBBWW", "7 3\nWBWBWBW", "6 4\nBWBWBW"] | 1 second | ["WBBBWW", "WWWWWWW", "BWBWBW"] | NoteThe first example is described in the statement.The second example: "WBWBWBW" $$$\rightarrow$$$ "WWBWBWW" $$$\rightarrow$$$ "WWWBWWW" $$$\rightarrow$$$ "WWWWWWW". So all chips become white.The third example: "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW" $$$\rightarrow$$$ "WBWBWB" $$$\rightarrow$$$ "BWBWBW". | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 86d17fa4bac5edd0cc4b6bff1c9899b7 | The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ β the number of chips and the number of iterations, respectively. The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially. | 2,300 | Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B". | standard output | |
PASSED | ffcf72707630d7d95c45a251106ac181 | train_000.jsonl | 1582473900 | The biggest event of the year β Cota 2 world championship "The Innernational" is right around the corner. $$$2^n$$$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from $$$1$$$ to $$$2^n$$$ and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with $$$2^{n-1}$$$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $$$2^k$$$ teams play a game with each other (teams are split into games by team numbers). $$$2^{k-1}$$$ loosing teams are eliminated from the championship, $$$2^{k-1}$$$ winning teams are playing $$$2^{k-1}$$$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $$$2^{k-1}$$$ teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers $$$a_1, a_2, ..., a_k$$$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of? | 512 megabytes | //package round623;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
public class B {
InputStream is;
PrintWriter out;
String INPUT = "";
int[] cum;
void solve()
{
// 8 4 2 1
// +4 2 +2=4 2 1 +1=2 1 last
int n = ni(), K = ni();
if(K == 0) {
out.println(0);
return;
}
int[] a = na(K);
cum = new int[(1<<n)+1];
for(int v : a) {
cum[v]++;
}
for(int i = 1;i <= 1<<n;i++) {
cum[i] += cum[i-1];
}
long ret = dfs(0, 1<<n, 1, 0) + 2;
ret = Math.max(ret, dfs(0, 1<<n, 0, 1) + 2);
ret = Math.max(ret, dfs(0, 1<<n, 1, 1) + 2);
ret = Math.max(ret, dfs(0, 1<<n, 2, 0) + 2);
ret = Math.max(ret, dfs(0, 1<<n, 2, 1) + 2);
out.println(ret);
}
Map<Long, Long> cache = new HashMap<>();
long dfs(int l, int r, int wn, int ln)
{
long code = 0;
code = code * 1000000009 + l;
code = code * 1000000009 + r;
code = code * 1000000009 + wn;
code = code * 1000000009 + ln;
if(cache.containsKey(code))return cache.get(code);
int h = l+r>>1;
if(r-l == 4) {
int nr = cum[r] - cum[h];
int nl = cum[h] - cum[l];
if(nl > nr) {
int d = nl; nl = nr; nr = d;
}
if(nl == 0) {
if(nr == 0) {
return wn + ln == 0 ? 0 : Long.MIN_VALUE / 3;
}else if(nr == 1) {
return wn + ln == 1 ? 2 : Long.MIN_VALUE / 3;
}else {
return wn == 1 && ln == 1 ? 3 : Long.MIN_VALUE / 3;
}
}else if(nl == 1) {
if(nr == 1) {
if(wn == 1 && ln == 1)return 4;
if(wn == 2 && ln == 0)return 3;
if(wn == 0 && ln == 1)return 3;
return Long.MIN_VALUE / 3;
}else {
if(wn == 2 && ln == 1)return 4;
if(wn == 1 && ln == 1)return 4;
return Long.MIN_VALUE / 3;
}
}else if(nl == 2) {
if(wn == 2 && ln == 1)return 4;
return Long.MIN_VALUE / 3;
}
throw new RuntimeException();
}
long[] lptn = new long[4];
Arrays.fill(lptn, Long.MIN_VALUE / 3);
for(int lw = 0;lw <= 2;lw++) {
for(int ll = 0;ll <= 1;ll++) {
long v = dfs(l, h, lw, ll);
if(lw == 2) {
lptn[3] = Math.max(lptn[3], v + 1);
}else if(lw == 0) {
lptn[ll<<1] = Math.max(lptn[ll<<1], v + ll);
}else if(ll == 1) {
lptn[3] = Math.max(lptn[3], v + 1);
lptn[2] = Math.max(lptn[2], v + 1);
}else {
lptn[1] = Math.max(lptn[1], v);
lptn[2] = Math.max(lptn[2], v + 1);
}
}
}
long[] rptn = new long[4];
Arrays.fill(rptn, Long.MIN_VALUE / 3);
for(int lw = 0;lw <= 2;lw++) {
for(int ll = 0;ll <= 1;ll++) {
long v = dfs(h, r, lw, ll);
if(lw == 2) {
rptn[3] = Math.max(rptn[3], v + 1);
}else if(lw == 0) {
rptn[ll<<1] = Math.max(rptn[ll<<1], v + ll);
}else if(ll == 1) {
rptn[3] = Math.max(rptn[3], v + 1);
rptn[2] = Math.max(rptn[2], v + 1);
}else {
rptn[1] = Math.max(rptn[1], v);
rptn[2] = Math.max(rptn[2], v + 1);
}
}
}
// tr(l, r, wn, ln, lptn, rptn);
long ret = Long.MIN_VALUE / 3;
for(int i = 0;i < 4;i++) {
for(int j = 0;j < 4;j++) {
for(int k = (i&j)&1;k <= ((i|j)&1);k++) {
for(int m = ((i&j)&2)>>1;m <= ((i|j)&2)>>1;m++) {
if(k == wn && m == ln) {
ret = Math.max(ret, lptn[i] + rptn[j] + k + m);
}
}
}
}
}
cache.put(code, ret);
return ret;
}
void run() throws Exception
{
// int n = 17, m = 99999;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(m + " ");
// Set<Integer> set = new HashSet<>();
// for (int i = 0; i < m; i++) {
// while(true) {
// int x = gen.nextInt(1<<17)+1;
// if(set.add(x)) {
// sb.append(x + " ");
// break;
// }
// }
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new B().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3 1\n6", "3 3\n1 7 8", "3 4\n1 3 5 7"] | 2 seconds | ["6", "11", "14"] | NoteOn the image, each game of the championship is denoted with an English letter ($$$a$$$ to $$$n$$$). Winner of game $$$i$$$ is denoted as $$$Wi$$$, loser is denoted as $$$Li$$$. Teams you're a fan of are highlighted with red background.In the first example, team $$$6$$$ will play in 6 games if it looses the first upper bracket game (game $$$c$$$) and wins all lower bracket games (games $$$h, j, l, m$$$). In the second example, teams $$$7$$$ and $$$8$$$ have to play with each other in the first game of upper bracket (game $$$d$$$). Team $$$8$$$ can win all remaining games in upper bracket, when teams $$$1$$$ and $$$7$$$ will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. | Java 11 | standard input | [
"dp",
"implementation"
] | 43501b998dbf4c4fef891a8591e32a42 | First input line has two integers $$$n, k$$$Β β $$$2^n$$$ teams are competing in the championship. You are a fan of $$$k$$$ teams ($$$2 \le n \le 17; 0 \le k \le 2^n$$$). Second input line has $$$k$$$ distinct integers $$$a_1, \ldots, a_k$$$Β β numbers of teams you're a fan of ($$$1 \le a_i \le 2^n$$$). | 2,500 | Output single integerΒ β maximal possible number of championship games that include teams you're fan of. | standard output | |
PASSED | 896255e651557b57fb9a9800a51d1496 | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
final InputReader in = oj ? new InputReader(System.in) : new InputReader(new FileInputStream(new File("in.txt")));
final PrintWriter out = new PrintWriter(System.out);
new TaskB().solve(in, out);
out.close();
}
static class TaskB {
void solve(InputReader in, PrintWriter out) {
int n = in.nextInt(), k = in.nextInt();
List<Integer> pillars = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
pillars.add(in.nextInt());
}
List<Map.Entry> path = new ArrayList<>();
while (k > 0) {
int max = maxPosition(pillars);
int min = minPosition(pillars);
if (max == min) break;
/*
boolean b = false;
for (Map.Entry e : path) {
if (e.getValue() == max) {
b = true;
break;
}
}
if (b) break;
*/
pillars.set(max, pillars.get(max) - 1);
pillars.set(min, pillars.get(min) + 1);
path.add(new AbstractMap.SimpleEntry<>(max, min));
k--;
}
int max = maxPosition(pillars);
int min = minPosition(pillars);
out.println(String.format("%d %d", Math.abs(pillars.get(max) - pillars.get(min)), path.size()));
for (Map.Entry<Integer, Integer> p : path) {
out.println(String.format("%d %d", p.getKey() + 1, p.getValue() + 1));
}
}
int maxPosition(List<Integer> list) {
int max = list.get(0);
int result = 0;
for (int i = 1; i < list.size(); i++) {
Integer e = list.get(i);
if (e > max) {
max = e;
result = i;
}
}
return result;
}
int minPosition(List<Integer> list) {
int min = list.get(0);
int result = 0;
for (int i = 1; i < list.size(); i++) {
Integer e = list.get(i);
if (e < min) {
min = e;
result = i;
}
}
return result;
}
}
static class TaskA {
void solve(InputReader in, PrintWriter out) {
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
int max = -1;
// a*b*c
if (a * b * c > max) max = a * b * c;
// a*b+c
if (a * b + c > max) max = a * b + c;
// a+b*c
if (a + b * c > max) max = a + b * c;
// a+b+c
if (a + b + c > max) max = a + b + c;
// a*(b+c)
if (a * (b + c) > max) max = a * (b + c);
// (a+b)*c
if ((a + b) * c > max) max = (a + b) * c;
out.println(max);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
this.tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 093905c4d2affa2458aec67190bdc28e | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.*;
import static java.lang.Long.*;
public class B274 {
int INF = Integer.MAX_VALUE / 100;
static Scanner sc = null;
static BufferedReader br = null;
static PrintStream out = null;
static BufferedWriter bw = null;
int N = 0;
public void solve() throws Exception{
int[] tp = nextInts();
int n = tp[0];
int k = tp[1];
int[] d = nextInts();
D[] ds = new D[n];
for(int i = 0; i < d.length; i++){
ds[i] = new D();
ds[i].d = d[i];
ds[i].idx = i + 1;
}
Arrays.sort(ds, new Comparator<D>() {
@Override
public int compare(D o1, D o2) {
// TODO Auto-generated method stub
return o1.d - o2.d;
}
});
if(n == 1){
System.out.println("0 0");
return;
}
List<String> as = new ArrayList<String>();
List<String> suba = new ArrayList<String>();
while(k > 0){
int bdiff = ds[n-1].d - ds[0].d;
if(bdiff <= 1){
break;
}
ds[0].d +=1;
ds[n-1].d --;
suba.add(ds[n-1].idx + " " + ds[0].idx);
Arrays.sort(ds, new Comparator<D>() {
@Override
public int compare(D o1, D o2) {
// TODO Auto-generated method stub
return o1.d - o2.d;
}
});
k--;
int adiff = ds[n-1].d - ds[0].d;
if(adiff < bdiff){
as.addAll(suba);
suba.clear();
}
}
int cdiff = ds[n-1].d - ds[0].d;
int op = as.size();
System.out.println(cdiff + " " + op);
for(int i = 0; i < as.size(); i++){
System.out.println(as.get(i));
}
}
class D{
int idx = 0;
int d = 0;
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = sc.nextInt();
}
return ret;
}
private String nextS() throws IOException{
String s = br.readLine();
return s;
}
private int nextInt() throws IOException{
String s = br.readLine();
return parseInt(s);
}
private long nextLong() throws IOException{
String s = br.readLine();
return parseLong(s);
}
private int[] nextInts() throws IOException{
String s = br.readLine();
String[] sp = s.split(" ");
int[] r = new int[sp.length];
for(int i = 0;i < sp.length; i++){
r[i] = parseInt(sp[i]);
}
return r;
}
private long[] nextLongs() throws IOException{
String s = br.readLine();
String[] sp = s.split(" ");
long[] r = new long[sp.length];
for(int i = 0;i < sp.length; i++){
r[i] = parseLong(sp[i]);
}
return r;
}
void pl(String s){
try{
bw.write(s);
}
catch(Exception ex){
}
}
void pln(String s){
try{
bw.write(s);
bw.write(System.lineSeparator());
}
catch(Exception ex){
}
}
void pln(){
try{
bw.write(System.lineSeparator());
}
catch(Exception ex){
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
File file = new File("input.txt");
if(file.exists()){
System.setIn(new BufferedInputStream(new FileInputStream("input.txt")));
}
out = System.out;
bw = new BufferedWriter(new PrintWriter(out));
//sc = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
B274 t = new B274();
t.solve();
bw.close();
}
}
| Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | f3ef419cedb50cd6cb3f54bacc80650c | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
Tower [] a = new Tower[n];
for (int i=0; i<n; i++) {
a[i] = new Tower(in.nextInt(), i+1);
}
if (n == 1) {
out.println("0 0");
return;
}
Arrays.sort(a);
int d = a[n-1].v - a[0].v;
StringBuilder sb = new StringBuilder();
int r = 0;
while (r < k && d > 1) {
sb.append(a[n-1].index + " " + a[0].index + "\n");
r++;
a[n-1].v--;
a[0].v++;
Arrays.sort(a);
d = a[n-1].v - a[0].v;
}
out.println(d + " " + r);
out.println(sb);
}
class Tower implements Comparable<Tower> {
int v;
int index;
Tower(int t, int i) {
v = t;
index = i;
}
@Override
public int compareTo(Tower t) {
if (v < t.v) {
return -1;
} else if (v > t.v) {
return 1;
}
return 0;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader in) {
br = new BufferedReader(in);
}
String nextLine() {
String str = null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
B o = new B();
o.run();
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 3b855ac7d8b48dfed1bce766bc41fb80 | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.util.*;
public class B
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] t = new int[n];
PriorityQueue<Integer> max = new PriorityQueue<Integer>(1, new Rev());
PriorityQueue<Integer> min = new PriorityQueue<Integer>();
int ave = 0;
for(int i=0; i<n; i++)
{
t[i] = in.nextInt();
min.add(t[i]);
max.add(t[i]);
ave+=t[i];
}
ave = (int)Math.round(((double)ave/(double)n));
int trans = 0;
String pr = "";
while(trans<k)
{
int a = max.peek();
int b = min.peek();
if(a==ave || b==ave)
break;
max.poll();
min.poll();
trans++;
max.add(a-1);
min.add(b+1);
int ai = -1;
int bi = -1;
for(int i=0; i<n; i++)
{
if(t[i]==a)
ai = i;
if(t[i]==b)
bi = i;
}
t[ai]--;
t[bi]++;
pr += (ai+1) + " " + (bi+1) + "\n";
}
System.out.println(Math.abs(max.peek()-min.peek()) + " " + trans);
System.out.print(pr);
}
}
class Rev implements Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
return -1*Integer.compare(a, b);
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | c7a5853fef330c6ac06ba27997c7a03e | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
}
class TaskA {
public void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int tab[] = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = in.nextInt();
}
int count = 0;
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
int min=-1,max=-1,maxIndex=-1,minIndex = -1;
for (int i = 0; i < k; i++) {
max = Integer.MIN_VALUE;
maxIndex = -1;
minIndex = -1;
min = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if(tab[j] > max) {
max = tab[j];
maxIndex = j;
}
if(tab[j] < min) {
min = tab[j];
minIndex = j;
}
}
if(max <= min + 1) {
break;
}
count++;
first.add(maxIndex+1);
second.add(minIndex+1);
tab[minIndex]++;
tab[maxIndex]--;
}
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
min = Math.min(min, tab[i]);
max = Math.max(max, tab[i]);
}
out.printLine((max - min) + " " + count);
for (int i = 0; i < first.size(); i++) {
out.printLine(first.get(i) + " " + second.get(i));
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 8a7e40369d8c75e17b4ae7978e8071aa | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
public class Main {
// public static int w;
// public static int k;
// public static int n;
// public static int[][] dp;
// public static int[] r;
// public static long[] buy;
// public static List<double[]> list = new ArrayList<double[]>();
// public static NodeW[] product;
// public static int[][] dists;
// public static int x;
// public static int[][] memo;
// public static String str;
// public static HashSet<String> set;
public static void main(String[] args) throws NumberFormatException, IOException{
ContestScanner in = new ContestScanner();
int n = in.nextInt();
int k = in.nextInt();
int[][] a = new int[n][2];
for(int i=0; i<n; i++){
a[i][0] = in.nextInt();
a[i][1] = i;
}
MyComp cmp = new MyComp();
Arrays.sort(a, cmp);
StringBuilder bld = new StringBuilder();
int line = 0;
while(k>0 && a[n-1][0]-a[0][0] > 1){
a[n-1][0]--;
a[0][0]++;
bld.append((a[n-1][1]+1)+" "+(a[0][1]+1)+"\n");
Arrays.sort(a, cmp);
line++;
k--;
}
System.out.println((a[n-1][0]-a[0][0])+" "+line);
System.out.print(bld.toString());
}
}
class MyComp implements Comparator<int[]>{
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
}
class Reverse implements Comparator<Integer>{
public int compare(Integer arg0, Integer arg1) {
return arg1 - arg0;
}
}
class Node{
int id;
List<Node> edge = new ArrayList<Node>();
public Node(int id){
this.id = id;
}
public void createEdge(Node node){
edge.add(node);
}
}
class NodeW{
int id;
// int dist;
List<NodeW> edge = new ArrayList<NodeW>();
List<Integer> costList = new ArrayList<Integer>();
public NodeW(int id) {
this.id = id;
}
public void createEdge(NodeW node, int cost) {
edge.add(node);
costList.add(cost);
// node.setDist(dist+1);
}
// public void setDist(int dist){
// this.dist = Math.max(this.dist, dist);
// for(NodeW node: edge){
// node.setDist(dist+1);
// }
// }
}
class Range<T extends Comparable<T>> implements Comparable<Range<T>>{
T start;
T end;
public Range(T start, T end){
this.start = start;
this.end = end;
}
public boolean inRange(T val){
if(start.compareTo(val) <= 0 && end.compareTo(val) >= 0){
return true;
}
return false;
}
public boolean isCommon(Range<T> range){
if(inRange(range.start) || inRange(range.end) || range.inRange(start)){
return true;
}
return false;
}
public Range<T> connect(Range<T> range){
if(!isCommon(range)) return null;
Range<T> res = new Range<T>(start.compareTo(range.start) <= 0 ? start : range.start,
end.compareTo(range.end) >= 0 ? end : range.end);
return res;
}
public boolean connectToThis(Range<T> range){
if(!isCommon(range)) return false;
start = start.compareTo(range.start) <= 0 ? start : range.start;
end = end.compareTo(range.end) >= 0 ? end : range.end;
return true;
}
@Override
public int compareTo(Range<T> range) {
int res = start.compareTo(range.start);
if(res == 0) return end.compareTo(range.end);
return res;
}
public String toString(){
return "["+start+","+end+"]";
}
}
class RangeSet<T extends Comparable<T>>{
TreeSet<Range<T>> ranges = new TreeSet<Range<T>>();
public void add(Range<T> range){
Range<T> con = ranges.floor(range);
if(con != null){
if(con.connectToThis(range))
range = con;
}
con = ranges.ceiling(range);
while(con != null && range.connectToThis(con)){
ranges.remove(con);
con = ranges.ceiling(range);
}
ranges.add(range);
}
public String toString(){
StringBuilder bld = new StringBuilder();
for(Range<T> r: ranges){
bld.append(r+"\n");
}
return bld.toString();
}
}
class MyMath{
public static long fact(long n){
long res = 1;
while(n > 0){
res *= n--;
}
return res;
}
public static long[][] pascalT(int n){
long[][] tri = new long[n][];
for(int i=0; i<n; i++){
tri[i] = new long[i+1];
for(int j=0; j<i+1; j++){
if(j == 0 || j == i){
tri[i][j] = 1;
}else{
tri[i][j] = tri[i-1][j-1] + tri[i-1][j];
}
}
}
return tri;
}
}
class ContestScanner{
private BufferedReader reader;
private String[] line;
private int idx;
public ContestScanner() throws FileNotFoundException{
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String nextToken() throws IOException{
if(line == null || line.length <= idx){
line = reader.readLine().trim().split(" ");
idx = 0;
}
return line[idx++];
}
public long nextLong() throws IOException, NumberFormatException{
return Long.parseLong(nextToken());
}
public int nextInt() throws NumberFormatException, IOException{
return (int)nextLong();
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(nextToken());
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 4cecb55f7767ac0c3a429686cf131d55 | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int towernum = sc.nextInt();
int openum = sc.nextInt();
int[] tower = new int[towernum];
for(int i = 0; i < towernum; i++){
tower[i] = sc.nextInt();
}
int[] answers = new int[openum];
int countope = 0;
for(int i = 0; i < openum; i++){
int max = tower[0];
int min = tower[0];
int maxindex = 0;
int minindex = 0;
for(int j = 1; j < towernum; j++){
if(tower[j] > max){
max = tower[j];
maxindex = j;
}else if(tower[j] < min){
min = tower[j];
minindex = j;
}
}
if(max - min <= 1){
break;
}
answers[i] = (maxindex + 1) * 1000 + (minindex + 1);
tower[maxindex]--;
tower[minindex]++;
countope++;
}
int lastmax = tower[0];
int lastmin = tower[0];
for(int i = 0; i < towernum; i++){
if(tower[i] > lastmax){
lastmax = tower[i];
}else if(tower[i] < lastmin){
lastmin = tower[i];
}
}
System.out.println((lastmax - lastmin) + " " + countope);
for(int i = 0; i < countope; i++){
System.out.println((answers[i]/1000) + " " + (answers[i] % 1000));
}
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 14d441f57ff46714992838c71768a171 | train_000.jsonl | 1413709200 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. | 256 megabytes | import java.io.*;
import java.util.*;
public class Towers
{
public static void main(String[] args) throws IOException
{
//Locale.setDefault (Locale.US);
Reader in = new Reader();
StringBuilder out = new StringBuilder();
int n, k, j, min, c, max;
int[] a;
for (int i = 0; i < 1; i++) {
n = in.nextInt();
k = in.nextInt();
a = new int[n];
for ( j = 0; j < n; j++)
a[j] = in.nextInt();
c = 0;
for ( ; k > 0 && a.length > 0; ) {
min = max = 0;
for (int l = 0; l < a.length; l++)
if(a[l] < a[min])
min = l;
else if(a[l] > a[max])
max = l;
if(a[min]+1 == a[max] || a[min] == a[max])
break;
else
{
out.append((max+1)+" "+(min+1)+"\n");
a[max]--;
a[min]++;
k--;
c++;
}
}
min = max = 0;
for (int l = 0; l < a.length; l++)
if(a[l] < a[min])
min = l;
else if(a[l] > a[max])
max = l;
System.out.print((a[max]-a[min])+" "+c+"\n"+out);
out = new StringBuilder();
}
}
static class Reader
{
BufferedReader br;
StringTokenizer st;
Reader() { // To read from the standard input
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(int i) throws IOException { // To read from a file
br = new BufferedReader(new FileReader("Sample Input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException { return Integer.parseInt(next()); }
long nextLong() throws IOException { return Long.parseLong(next()); }
double nextDouble() throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException { return br.readLine(); }
}
} | Java | ["3 2\n5 8 5", "3 4\n2 2 4", "5 3\n8 3 2 6 3"] | 1 second | ["0 2\n2 1\n2 3", "1 1\n3 2", "3 3\n1 3\n1 2\n1 3"] | NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Java 7 | standard input | [
"greedy",
"constructive algorithms",
"implementation",
"sortings",
"brute force"
] | 9cd42fb28173170a6cfa947cb31ead6d | The first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights. | 1,400 | In the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. | standard output | |
PASSED | 3f2bb879b2608cc6d544afa621eaa8fc | train_000.jsonl | 1529166900 | You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
class O implements Comparable<O> {
int power, proc;
public O(int power, int proc) {
this.power = power;
this.proc = proc;
}
@Override
public int compareTo(O o) {
if (power == o.power) {
return -Integer.compare(proc, o.proc);
}
return Integer.compare(o.power, power);
}
@Override
public String toString() {
return "O{" +
"power=" + power +
", proc=" + proc +
'}';
}
}
void solve() {
int n = in.nextInt();
O[] a = new O[n];
int[] pw = new int[n];
for (int i = 0; i < n; i++) {
pw[i] = in.nextInt();
}
int[] pr = new int[n];
for (int i = 0; i < n; i++) {
pr[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
a[i] = new O(pw[i], pr[i]);
}
Arrays.sort(a);
// System.err.println(Arrays.toString(a));
final int MAGIC = 101;
long[][] dp = new long[n + 1][MAGIC * n + 1];
long[][] ndp = new long[n + 1][MAGIC * n + 1];
for (int x = 0; x <= n; x++) {
Arrays.fill(dp[x], Long.MAX_VALUE);
Arrays.fill(ndp[x], Long.MAX_VALUE);
}
dp[0][0] = 0;
for (int i = 0; i < n; ) {
int j = i;
while (j != n && a[i].power == a[j].power) {
j++;
}
int curLen = j - i;
for (int canCover = 0; canCover <= n; canCover++) {
for (int proc = 0; proc <= i * MAGIC; proc++) {
long val = dp[canCover][proc];
if (val == Long.MAX_VALUE) {
continue;
}
int must = Math.max(0, curLen - canCover);
long sumPower = val;
int sumProc =proc;
for (int use = 0; use <= curLen; use++) {
if (use != 0) {
sumPower += a[i + use - 1].power;
sumProc += a[i + use - 1].proc;
}
if (use >= must) {
int nextCanCover = canCover + use * 2 - curLen;
ndp[nextCanCover][sumProc] = Math.min(ndp[nextCanCover][sumProc], sumPower);
}
}
}
}
swap(dp, ndp);
i = j;
}
long ans = Long.MAX_VALUE;
for (int can =0 ; can <= n;can++) {
for (int proc = 1; proc <= n * MAGIC; proc++) {
long pow =dp[can][proc];
if (pow == Long.MAX_VALUE ) {
continue;
}
ans = Math.min(ans, (pow * 1000 + proc - 1) / proc);
}
}
out.println(ans);
}
void swap(long[][] a, long[][] b) {
for (int i =0 ; i < a.length; i++) {
long[] tmp = a[i];
a[i] = b[i];
b[i] =tmp;
Arrays.fill(b[i], Long.MAX_VALUE);
}
}
void run() {
try {
in = new FastScanner(new File("A.in"));
out = new PrintWriter(new File("A.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().runIO();
}
} | Java | ["6\n8 10 9 9 8 10\n1 1 1 1 1 1", "6\n8 10 9 9 8 10\n1 10 5 5 1 10"] | 1 second | ["9000", "1160"] | NoteIn the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round. | Java 8 | standard input | [
"dp",
"binary search",
"greedy"
] | 8883f8124092ace99ce0309fb8a511aa | The first line contains a single integer n (1ββ€βnββ€β50) β the number of tasks. The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β108), where ai represents the amount of power required for the i-th task. The third line contains n integers b1,βb2,β...,βbn (1ββ€βbiββ€β100), where bi is the number of processors that i-th task will utilize. | 2,500 | Print a single integer value β the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up. | standard output | |
PASSED | 558ae407e2fc1c4a9a659c2f5e628c49 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 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.Arrays;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyInput in = new MyInput(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, MyInput in, PrintWriter out) {
int h = in.nextInt();
int w = in.nextInt();
char[][] cs = new char[h][];
for (int y = 0; y < h; y++) {
cs[y] = in.nextChars();
}
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++)
if (cs[y][x] == '#') {
List<Integer> setX = new ArrayList<>();
List<Integer> setY = new ArrayList<>();
for (int x1 = 0; x1 < w; x1++) {
if (cs[y][x1] == '#') {
setX.add(x1);
}
}
for (int y1 = 0; y1 < h; y1++) {
if (cs[y1][x] == '#') {
setY.add(y1);
}
}
// dump(setX, setY);
for (int xx : setX) {
for (int yy : setY) {
if (cs[yy][xx] != '#') {
out.println("No");
return;
}
}
}
}
}
out.println("Yes");
}
}
static class MyInput {
private final BufferedReader in;
private static int pos;
private static int readLen;
private static final char[] buffer = new char[1024 * 8];
private static char[] str = new char[500 * 8 * 2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for (int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public MyInput(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public int read() {
if (pos >= readLen) {
pos = 0;
try {
readLen = in.read(buffer);
} catch (IOException e) {
throw new RuntimeException();
}
if (readLen <= 0) {
throw new MyInput.EndOfFileRuntimeException();
}
}
return buffer[pos++];
}
public int nextInt() {
int len = 0;
str[len++] = nextChar();
len = reads(len, isSpace);
int i = 0;
int ret = 0;
if (str[0] == '-') {
i = 1;
}
for (; i < len; i++) ret = ret * 10 + str[i] - '0';
if (str[0] == '-') {
ret = -ret;
}
return ret;
}
public char nextChar() {
while (true) {
final int c = read();
if (!isSpace[c]) {
return (char) c;
}
}
}
int reads(int len, boolean[] accept) {
try {
while (true) {
final int c = read();
if (accept[c]) {
break;
}
if (str.length == len) {
char[] rep = new char[str.length * 3 / 2];
System.arraycopy(str, 0, rep, 0, str.length);
str = rep;
}
str[len++] = (char) c;
}
} catch (MyInput.EndOfFileRuntimeException e) {
}
return len;
}
public char[] nextChars() {
int len = 0;
str[len++] = nextChar();
len = reads(len, isSpace);
return Arrays.copyOf(str, len);
}
static class EndOfFileRuntimeException extends RuntimeException {
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 9a32dc18e23e1b3e2d17ef2f84c9a7df | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 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.HashSet;
import java.util.StringTokenizer;
public class MysticalMosaic {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int cols=sc.nextInt();
HashSet<Long>set=new HashSet<Long>();
ArrayList<boolean[]>arr=new ArrayList<boolean[]>();
while(rows-->0) {
long x=0;
boolean[]c=new boolean[cols];
String s=sc.next();
for(int i=0;i<cols;++i)
if(s.charAt(i)=='#') {
c[i]=true;
x+=(1<<i);
}
if(!set.contains(x)) {
set.add(x);
arr.add(c);
}
}
int cntTrue=0;
boolean can=true;
for(int i=0;i<cols && can;++i) {
cntTrue=0;
for(int j=0;j<arr.size()&& can;++j) {
if(arr.get(j)[i])
cntTrue++;
if(cntTrue>=2)
can=false;
}
}
System.out.println(can?"Yes":"No");
}
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 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 25fd9a03a3c2f7283f42eb26d9dcd72b | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
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();
}
static class TaskA {
void find(int row, int col, TreeSet<Integer> rows, TreeSet<Integer> cols, boolean[][] shouldSelect, boolean[][] selectedHere) {
if (selectedHere[row][col]) return;
selectedHere[row][col] = true;
rows.add(row);
cols.add(col);
for (int otherCol = 0; otherCol < shouldSelect[0].length; otherCol++) {
if (shouldSelect[row][otherCol]) {
find(row, otherCol, rows, cols, shouldSelect, selectedHere);
}
}
for (int otherRow = 0; otherRow < shouldSelect.length; otherRow++) {
if (shouldSelect[otherRow][col]) {
find(otherRow, col, rows, cols, shouldSelect, selectedHere);
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int rows = in.readInt();
int cols = in.readInt();
char[][] tab = new char[rows][];
for (int row = 0; row < tab.length; row++) {
tab[row] = in.next().toCharArray();
}
boolean[][] shouldSelect = new boolean[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
shouldSelect[row][col] = (tab[row][col] == '#');
}
}
boolean[][] selected = new boolean[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (shouldSelect[row][col] && !selected[row][col]) {
// then we select it here
TreeSet<Integer> rowResult = new TreeSet<>();
TreeSet<Integer> colResult = new TreeSet<>();
boolean[][] selectHere = new boolean[rows][cols];
find(row, col, rowResult, colResult, shouldSelect, selectHere);
for (int rr : rowResult) {
for (int cc : colResult) {
selected[rr][cc] = true;
}
}
}
}
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (shouldSelect[row][col] && !selected[row][col]) {
throw new RuntimeException();
}
if (!shouldSelect[row][col] && selected[row][col]) {
out.printLine("No");
return;
}
}
}
out.printLine("Yes");
}
}
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 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);
}
}
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 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();
}
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | fc3681cfe8a4adad882e86dd65f31d2c | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes |
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner i = new Scanner(System.in);
int n,m;
n = i.nextInt();
m= i.nextInt();
Vector<String>work = new Vector<String>(n);
Vector<Integer>rows = new Vector<Integer>();
Vector<Integer>cols = new Vector<Integer>();
for (int j = 0; j < n; j++) {
work.addElement(i.next());
}
for (int j = 0; j < n; j++) {
boolean same = true;
Vector<String> checkLength = new Vector<String>();
boolean anyHash = false;
for (int k = 0; k < m; k++) {
if(work.get(j).charAt(k)== '#')
{
anyHash = true;
if (
(rows.contains(new Integer(j)) || cols.contains(new Integer(k)))
&&
same
)
{
System.out.print("No");
return;
}else{
cols.add(new Integer(k));
String count = "";
for (int u = j; u <n ; u++) {
if(work.get(u).charAt(k) == '#')
{
if (rows.contains(new Integer(u)) && same)
{
System.out.print("No");
return;
}
count += Integer.toString(u);
char[] bChars = work.get(u).toCharArray();
bChars[k] = '.';
work.set(u, String.valueOf(bChars)) ;
rows.add(new Integer(u));
}
}
if(!checkLength.contains(count))
{
checkLength.add(count);
}
}
same = false;
}
}
if(anyHash)
{
if(checkLength.size() != 1)
{
System.out.println("No");
return;
}
}
}
System.out.println("Yes");
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | f7a777f139c0bfddd73b68165071ca7e | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
AMysticalMosaic solver = new AMysticalMosaic();
solver.solve(1, in, out);
out.close();
}
}
static class AMysticalMosaic {
int n;
int m;
public void solve(int testNumber, FastInput in, FastOutput out) {
n = in.readInt();
m = in.readInt();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = in.readChar() == '#' ? 1 : 0;
}
}
DSU dsu = new DSU(n + m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 1) {
dsu.merge(idOfRow(i), idOfCol(j));
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0 && dsu.find(idOfRow(i)) == dsu.find(idOfCol(j))) {
out.println("No");
return;
}
}
}
out.println("Yes");
}
public int idOfRow(int i) {
return i;
}
public int idOfCol(int i) {
return n + i;
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 20];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(String c) {
cache.append(c);
return this;
}
public FastOutput println(String c) {
return append(c).println();
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class DSU {
protected int[] p;
protected int[] rank;
public DSU(int n) {
p = new int[n];
rank = new int[n];
reset();
}
public final void reset() {
for (int i = 0; i < p.length; i++) {
p[i] = i;
rank[i] = 0;
}
}
public final int find(int a) {
if (p[a] == p[p[a]]) {
return p[a];
}
return p[a] = find(p[a]);
}
public final void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b) {
return;
}
if (rank[a] == rank[b]) {
rank[a]++;
}
if (rank[a] > rank[b]) {
p[b] = a;
} else {
p[a] = b;
}
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 3667ab836ec938e5c874a9b8d99aec28 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
char[][] c = new char[n][m];
for(int i=0; i<n; i++) {
c[i] = bf.readLine().toCharArray();
}
for(int i=0; i<n; i++) {
boolean[] black = new boolean[m];
for(int j=0; j<m; j++) black[j] = (c[i][j] == '#');
for(int row=i+1; row<n; row++) {
boolean all = true; boolean one = false; boolean other = false;
for(int j=0; j<m; j++) {
if(black[j]) {
if(c[row][j] != '#') all = false;
else one = true;
}
else if(c[row][j] == '#') other = true;
}
if(one && !all) {
out.println("No");
out.close();
System.exit(0);
}
else if(one && other) {
out.println("No");
out.close();
System.exit(0);
}
else if(one) {
for(int j=0; j<m; j++) {
if(black[j]) c[row][j] = '.';
}
}
}
}
// int[] a = new int[n];
// for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
out.println("Yes");
out.close(); System.exit(0);
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 565f1194a226f82f8be20dd2288ba2de | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/a.in"))));
/**/
int n = sc.nextInt();
int m = sc.nextInt();
List<List<Integer>> rows = new ArrayList<>();
List<List<Integer>> cols = new ArrayList<>();
for (int i = 0; i < n; i++) {
rows.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
cols.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
if (s.charAt(j)=='#') {
rows.get(i).add(j);
cols.get(j).add(i);
}
}
}
for (int i = 0; i < n; i++) {
if (rows.get(i).size() > 1) {
List<Integer> gtc = cols.get(rows.get(i).get(0));
for (int coli : rows.get(i)) {
List<Integer> test = cols.get(coli);
if (gtc.size() != test.size()) {
System.out.println("No");
return;
}
for (int j : gtc) {
if (!test.contains(j)) {
System.out.println("No");
return;
}
}
}
}
}
for (int i = 0; i < m; i++) {
if (cols.get(i).size() > 1) {
List<Integer> gtr = rows.get(cols.get(i).get(0));
for (int rowi : cols.get(i)) {
List<Integer> test = rows.get(rowi);
if (gtr.size() != test.size()) {
System.out.println("No");
return;
}
for (int j : gtr) {
if (!test.contains(j)) {
System.out.println("No");
return;
}
}
}
}
}
System.out.println("Yes");
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | eff75f137a51dd590dd1dbbe0e0bf23a | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static int []p;
static Random rm;
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 n = nextInt();
int m = nextInt();
char[][]a = new char[n][m];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
p = new int[n+m];
for (int i = 0; i < n+m; i++) {
p[i] = i;
}
rm = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j]=='#') {
unite(i, j+n);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == '.') {
int pi = getFath(i);
int pj = getFath(j+n);
if (pi==pj) {
System.out.println("No");
return;
}
}
}
}
System.out.println("Yes");
pw.close();
}
private static boolean unite(int i, int j) {
int pi = getFath(i);
int pj = getFath(j);
if (pi==pj)
return false;
if (rm.nextInt() % 2==0)
p[pi] = pj;
else
p[pj] = pi;
return true;
}
private static int getFath(int v) {
if (p[v]==v)
return v;
return p[v] = getFath(p[v]);
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 597bab48bc05d499173c4721e2e9fc17 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class A {
public static void main(String[] args) {
JS in = new JS();
int R = in.nextInt();
int C = in.nextInt();
int g[][] = new int[R][C];
for(int i = 0; i < R; i++) {
char c[] = in.next().toCharArray();
for(int j = 0; j < C; j++) {
g[i][j] = c[j] == '.' ? 0 : 1;
}
}
boolean good = true;
for(int sr = 0; sr < R; sr++) {
boolean useC[] = new boolean[C];
int cnt1 = 0;
for(int c = 0; c < C; c++) {
if(g[sr][c] == 1){
useC[c] = true;
cnt1++;
}
}
for(int r = 0; r < R; r++) {
int cnt2 = 0;
boolean use = false;
for(int c = 0; c < C; c++) {
if(g[r][c] == 1 && useC[c]) use = true;
if(g[r][c] == 1 && useC[c]) cnt2++;
}
if(use && cnt2 != cnt1) good = false;
}
}
for(int sc = 0; sc < C; sc++) {
boolean useR[] = new boolean[R];
int cnt1 = 0;
for(int r = 0; r < R; r++) {
if(g[r][sc] == 1){
useR[r] = true;
cnt1++;
}
}
for(int c = 0; c < C; c++) {
int cnt2 = 0;
boolean use = false;
for(int r = 0; r < R; r++) {
if(g[r][c] == 1 && useR[r]) use = true;
if(g[r][c] == 1 && useR[r]) cnt2++;
}
if(use && cnt2 != cnt1) good = false;
}
}
System.out.println(good?"Yes":"No");
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar();
boolean neg = c=='-';
if(neg)c=nextChar();
boolean fl = c=='.';
double cur = nextLong();
if(fl) return neg ? -cur/num : cur/num;
if(c == '.') {
double next = nextLong();
return neg ? -cur-next/num : cur+next/num;
}
else return neg ? -cur : cur;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | e2e80a930aef38661f1fb1da3adcc1bd | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.util.*;
public class pA {
void run() {
int hei = in.nextInt();
int wid = in.nextInt();
Set<String> set = new TreeSet<>();
for (int i = 0; i < hei; i++) {
set.add(in.next());
}
for (String s : set) {
for (String t : set) {
if (s.equals(t)) {
continue;
}
for (int i = 0; i < wid; i++) {
if (s.charAt(i) == '#' && t.charAt(i) == '#') {
out.println("No");
return;
}
}
}
}
out.println("Yes");
}
static MyScanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean stdStreams = true;
String fileName = pA.class.getSimpleName().replaceFirst("_.*", "").toLowerCase();
String inputFileName = fileName + ".in";
String outputFileName = fileName + ".out";
Locale.setDefault(Locale.US);
BufferedReader br;
if (stdStreams) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
br = new BufferedReader(new FileReader(inputFileName));
out = new PrintWriter(outputFileName);
}
in = new MyScanner(br);
int tests = 1;//in.nextInt();
for (int test = 0; test < tests; test++) {
new pA().run();
}
br.close();
out.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 8e919669031b0aee6d2bbc8d03d6e018 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.math.*;
import java.lang.*;
public class Main {
static String a[] = new String[55];
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
PrintWriter pr = new PrintWriter(System.out);
int n = fr.nextInt();
int m = fr.nextInt();
for(int i=1;i<=n;i++) a[i] = fr.next();
int flag = 1;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
int flag1=0,flag2=0;
for(int k=0;k<m;k++){
if(a[i].charAt(k)=='#' && a[j].charAt(k)=='.') flag2=1;
if(a[i].charAt(k)=='.' && a[j].charAt(k)=='#') flag2=1;
if(a[i].charAt(k)=='#' && a[j].charAt(k)=='#') flag1=1;
}
if(flag1==1 && flag2==1){
flag = 0;
break;
}
}
if(flag==0) break;
}
if(flag==1) pr.println("Yes");
else pr.println("No");
pr.close();
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 6f5fdd5274234326e530d522a0a106ff | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes |
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
int maxn=55;
static String ma[]=new String [55];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int m=in.nextInt();
for(int i=1;i<=n;i++) ma[i]=in.next();
int flag=1;
for(int i=1;i<=n;i++) {
for(int j=i+1;j<=n;j++) {
int flag1=0,flag2=0;
for(int k=0;k<m;k++) {
if(ma[i].charAt(k)=='#'&&ma[j].charAt(k)=='.') flag2=1;
if(ma[i].charAt(k)=='.'&&ma[j].charAt(k)=='#') flag2=1;
if(ma[i].charAt(k)=='#'&&ma[j].charAt(k)=='#') flag1=1;
}
//if(i==1&&j==5) System.out.println(flag1+" "+flag2);
if(flag1==1&&flag2==1) {flag=0;break;}
}
if(flag==0) break;
}
if(flag==1) System.out.println("Yes");
else System.out.println("No");
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | b8af6e535d1ccc505b9944c193a518c5 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class A {
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();
HashSet<Integer> rowsDone = new HashSet<>();
char[][] a = new char[n][m];
for (int i = 0; i < n; i++)
a[i] = sc.next().toCharArray();
for (int row = 0; row < n; row++) {
if (rowsDone.contains(row))
continue;
HashSet<Integer> rowsNeeded = new HashSet<>();
HashSet<Integer> colsNeeded = new HashSet<>();
Queue<Integer> rows = new LinkedList<>(), cols = new LinkedList<>();
rows.add(row);
while (!rows.isEmpty() || !cols.isEmpty()) {
if (!rows.isEmpty()) {
int curRow = rows.poll();
for (int j = 0; j < m; j++)
if (!colsNeeded.contains(j) && a[curRow][j] == '#') {
colsNeeded.add(j);
cols.add(j);
}
} else {
int curCol = cols.poll();
for (int i = 0; i < n; i++)
if (!rowsNeeded.contains(i) && a[i][curCol] == '#') {
rowsNeeded.add(i);
rows.add(i);
}
}
}
for (int roww : rowsNeeded)
for (int colss : colsNeeded)
if (a[roww][colss] != '#') {
System.out.println("No");
return;
}
}
System.out.println("Yes");
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) {
br = new BufferedReader(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();
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 4090cf925d74dc6a6a7c5741f2a659ff | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.TreeSet;
public final class CF_472_A {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
static long mod=1000000007;
static long MX=1000000000000000001L;
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
static int sign(long x){
if (x==0)
return 0;
if (x>0)
return 1;
return -1;
}
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
int n=reader.readInt();
int m=reader.readInt();
long[] map=new long[n];
for (int i=0;i<n;i++){
String s=reader.readString();
long msk=0;
for (int j=0;j<m;j++){
if (s.charAt(j)=='#')
msk|=1L<<j;
}
map[i]=msk;
}
String ans="Yes";
loop:for (int i=0;i<n;i++)
for (int j=i+1;j<n;j++){
long ms1=map[i];
long ms2=map[j];
if ((ms1&ms2)!=0 && (ms1!=ms2)){
ans="No";
break loop;
}
}
output(ans);
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
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();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 69807c697cb212daf841353488155f19 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.TreeSet;
public final class CF_472_A {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
static long mod=1000000007;
static long MX=1000000000000000001L;
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
static int sign(long x){
if (x==0)
return 0;
if (x>0)
return 1;
return -1;
}
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
int n=reader.readInt();
int m=reader.readInt();
HashSet<Long> bob=new HashSet<Long>();
for (int i=0;i<n;i++){
String s=reader.readString();
long msk=0;
for (int j=0;j<m;j++){
if (s.charAt(j)=='#')
msk|=1L<<j;
}
bob.add(msk);
}
ArrayList<Long> lst=new ArrayList<Long>();
for (long msk:bob)
lst.add(msk);
int L=lst.size();
String ans="Yes";
loop:for (int i=0;i<L;i++)
for (int j=i+1;j<L;j++){
long ms1=lst.get(i);
long ms2=lst.get(j);
if ((ms1&ms2)!=0){
ans="No";
break loop;
}
}
output(ans);
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
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();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 5e7dc44e83a2a9e61b3a0918c4176d8c | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CF956A {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int r = in.nextInt();
int c = in.nextInt();
boolean grid[][] = new boolean[r][c];
for (int i = 0; i < r; i++) {
String s = in.next();
for (int j = 0; j < c; j++) {
if (s.charAt(j) == '#') grid[i][j] = true;
}
}
System.out.println(solve(grid) ? "Yes" : "No");
}
private static boolean solve(boolean[][] grid) {
Set<Integer> rs = new HashSet<>();
Set<Integer> cs = new HashSet<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j]) {
Set<Integer> newRs = new HashSet<>();
Set<Integer> newCs = new HashSet<>();
getRC(grid, i, j, newRs, newCs);
if (!rs.containsAll(newRs) && !cs.containsAll(newCs)) {
for (Integer newR : newRs) {
for (Integer newC : newCs) {
if (grid[newR][newC]) {
grid[newR][newC] = false;
} else {
return false;
}
}
}
} else {
return false;
}
}
}
}
return true;
}
private static void getRC(boolean[][] grid, int i, int j, Set<Integer> newRs, Set<Integer> newCs) {
for (int k = 0; k < grid.length; k++) {
if (grid[k][j] && (!newRs.contains(k) || !newCs.contains(j))) {
newRs.add(k);
newCs.add(j);
getRC(grid, k, j, newRs, newCs);
}
}
for (int k = 0; k < grid[i].length; k++) {
if (grid[i][k] && (!newRs.contains(i) || !newCs.contains(k))) {
newRs.add(i);
newCs.add(k);
getRC(grid, i, k, newRs, newCs);
}
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 8347f459111c64f463c13fe2dcb0461a | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class A
{
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 sc=new FastReader();
int n=sc.nextInt();
int m=sc.nextInt();
StringBuilder[] tab=new StringBuilder[n];
for (int i=0;i<n;i++) {
tab[i]=new StringBuilder(sc.nextLine());
}
ArrayList<Integer> utilisecol=new ArrayList<>();
ArrayList<Integer> actuelcol=new ArrayList<>();
boolean oui=true;
for (int j=0;j<n;j++) {
int a=tab[j].length();
int act=j;
for (int i=0;i<a;i++) {
if (tab[act].charAt(i)=='#') {
boolean trouve=false;
for (int k=0;k<utilisecol.size();k++) {
if (utilisecol.get(k).intValue()==i) {
trouve=true;
oui=false;
j=n;
break;
}
}
if (trouve==false) {
actuelcol.add(i);
}
}
}
for (int i=act+1;i<n;i++) {
if (tab[act].toString().equals(tab[i].toString())) {
String tmp="";
for (int k=0;k<m;k++) {
tmp+=".";
}
tab[i]=new StringBuilder(tmp);
}
}
for (int i=0;i<actuelcol.size();i++) {
utilisecol.add(actuelcol.get(i).intValue());
}
actuelcol.clear();
}
if (oui) System.out.println("Yes");
else System.out.println("No");
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 54a54dac663d248fe9d500cf72be29fd | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static int mod = 1000000007;
static long inf = (long) 1e16;
static int n, m;
static ArrayList<Integer>[] ad;
static long[][][] memo;
static boolean f;
static boolean vis[];
static int[] sub;
static char[] a;
static ArrayList<Long> ar;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] g = new char[n][m];
for (int i = 0; i < n; i++)
g[i] = sc.nextLine().toCharArray();
boolean f = true;
all: for (int i = 0; i < n; i++) {
TreeSet<Integer> pos = new TreeSet<>();
for (int j = 0; j < m; j++)
if (g[i][j] == '#')
pos.add(j);
for (int ii = 0; ii < n; ii++) {
int c = 0;
for (int jj = 0; jj < m; jj++) {
if (g[ii][jj] == '#')
if (pos.contains(jj))
c++;
}
if(c>0 &&c!=pos.size()) {
f=false;
break all;
}
}
}
if (f)
out.println("Yes");
else
out.println("No");
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 int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 1f2f890198c64661c159db8ebbb5ce91 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 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 A_Round_472_Div1 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] map = new ArrayList[n];
ArrayList<Integer>[] col = new ArrayList[m];
for (int i = 0; i < m; i++) {
col[i] = new ArrayList();
}
String[] data = new String[n];
for (int i = 0; i < n; i++) {
data[i] = in.next();
map[i] = new ArrayList();
for (int j = 0; j < m; j++) {
if (data[i].charAt(j) == '#') {
map[i].add(j);
col[j].add(i);
}
}
}
boolean ok = true;
for(ArrayList<Integer> list : col){
for(int i = 1; i < list.size() && ok; i++ ){
int a = list.get(i);
int b = list.get(i - 1);
ok &= map[a].equals(map[b]);
}
if(!ok){
break;
}
}
if(ok){
out.println("Yes");
}else{
out.println("No");
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 32e2e0a4f172dff9f1a87a3a93ce0682 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("Test.in"));
PrintWriter pw = new PrintWriter(System.out);
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out"));
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
// System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore) / 1000000 );
// System.out.println("Time used: " + (TIME_END - TIME_START) + ".");
}
public static class Task {
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] grid = new int[n][m];
int black = 0;
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
int c = s.charAt(j) == '.' ? 0 : 1;
if (c >= 1) {
black++;
}
grid[i][j] = c;
}
}
int[] rowUse = new int[n];
int[] colUse = new int[m];
int iter = 0;
while (black > 0) {
iter++;
if (iter >= 100) {
pw.println("No");
return;
}
for (int i = 0; i < n; i++) {
List<Integer> consider = new ArrayList<>();
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
if (colUse[j] == 1 || rowUse[i] == 1) {
pw.println("No");
return;
}
colUse[j] = 1;
// grid[i][j] = 0;
// black--;
consider.add(j);
}
}
if (consider.size() > 0) {
for (int j = 0; j < n; j++) {
if (grid[j][consider.get(0)] == 1) {
if (rowUse[j] == 1) {
pw.println("No");
return;
}
rowUse[j] = 1;
for (int c : consider) {
if (grid[j][c] == 1) {
grid[j][c] = 0;
black--;
} else {
pw.println("No");
return;
}
}
}
}
}
}
}
pw.println("Yes");
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(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 { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 2e195a982d0f78df7dfa7f20b32b3b07 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(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, FastScanner in, PrintWriter out) {
int height = in.nextInt();
int width = in.nextInt();
long[] cs = new long[height];
for (int r = 0; r < height; r++) {
char[] s = in.next().toCharArray();
for (int c = 0; c < width; c++) {
if (s[c] == '#') {
cs[r] |= 1L << c;
}
}
}
for (int i = 0; i < height; i++) {
for (int j = i + 1; j < height; j++) {
if ((cs[i] & cs[j]) != 0 && cs[i] != cs[j]) {
out.println("No");
return;
}
}
}
out.println("Yes");
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 9d3ab0b122a239dcd884b7f498baf830 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<26).start();
}
void union(int i, int j) {
par[j] = i;
}
int findSet(int i) {
if(par[i] == i)
return i;
par[i] = findSet(par[i]);
return par[i];
}
int par[];
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] s = new char[n][m];
for(int i = 0; i < n; ++i)
s[i] = sc.next().toCharArray();
par = new int[n + m];
for(int i = 0; i < n + m; ++i)
par[i] = i;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(s[i][j] == '#') {
int val1 = findSet(i);
int val2 = findSet(n + j);
if(val1 != val2)
union(val1, val2);
}
}
}
int flag = 0;
for(int i = 0; i < n; ++i) {
int curp = findSet(i);
for(int j = 0; j < m; ++j) {
int parj = findSet(n + j);
if(curp == parj && s[i][j] != '#')
flag = 1;
}
}
if(flag == 0)
w.print("Yes");
else
w.print("No");
w.close();
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 899d76d0d7566363ce7486c59c735af3 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | //package round472;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
char[][] map = nm(n,m);
DJSet ds = new DJSet(n+m);
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(map[i][j] == '#'){
ds.union(i, n+j);
}
}
}
char[][] b = new char[n][m];
for(int i = 0;i < n;i++)Arrays.fill(b[i], '.');
for(int j = 0;j < n;j++){
for(int k = 0;k < m;k++){
if(ds.equiv(j, n+k)){
b[j][k] = '#';
}
}
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(map[i][j] != b[i][j]){
out.println("No");
return;
}
}
}
out.println("Yes");
}
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
public int count() {
int ct = 0;
for (int u : upper)
if (u < 0)
ct++;
return ct;
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | e829ee591a03d4cc6aa66a1feeba9692 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class A {
void submit() {
int n = nextInt();
int m = nextInt();
char[][] f = new char[n][];
for (int i = 0; i < n; i++) {
f[i] = nextToken().toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (Arrays.equals(f[i], f[j])) {
continue;
}
for (int k = 0; k < m; k++) {
if (f[i][k] == '#' && f[j][k] == '#') {
out.println("No");
return;
}
}
}
}
out.println("Yes");
}
void preCalc() {
}
void test() {
}
void stress() {
for (int tst = 0;; tst++) {
if (false) {
throw new AssertionError();
}
System.err.println(tst);
}
}
A() throws IOException {
is = System.in;
out = new PrintWriter(System.out);
preCalc();
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static final int C = 5;
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new A();
}
private InputStream is;
PrintWriter out;
private byte[] buf = new byte[1 << 14];
private int bufSz = 0, bufPtr = 0;
private int readByte() {
if (bufSz == -1)
throw new RuntimeException("Reading past EOF");
if (bufPtr >= bufSz) {
bufPtr = 0;
try {
bufSz = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufSz <= 0)
return -1;
}
return buf[bufPtr++];
}
private boolean isTrash(int c) {
return c < 33 || c > 126;
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isTrash(b))
;
return b;
}
String nextToken() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isTrash(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextString() {
int b = readByte();
StringBuilder sb = new StringBuilder();
while (!isTrash(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
char nextChar() {
return (char) skip();
}
int nextInt() {
int ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
long nextLong() {
long ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
}
| Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 484fa8e9416c69a7264038a27f9e0c82 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
private static int n,m;
private static char [] [] G;
private static boolean [] row,col;
private static LinkedList<Integer> R,C;
private static void dfs(int x,boolean is_row) {
if (is_row) {
R.add(x);
row[x] = true;
for (int i = 0;i < m;i++)
if (G[x][i] == '#' && !col[i])
dfs(i,false);
}
else {
C.add(x);
col[x] = true;
for (int i = 0;i < n;i++)
if (G[i][x] == '#' && !row[i])
dfs(i,true);
}
}
public static void main(String[] args) throws Exception {
IO io = new IO(null,null);
n = io.getNextInt();
m = io.getNextInt();
G = new char[n][m];
for (int i = 0;i < n;i++)
G[i] = io.getNext().toCharArray();
row = new boolean[n];
col = new boolean[m];
R = new LinkedList<>();
C = new LinkedList<>();
boolean y = true;
for (int i = 0;i < n && y;i++)
if (!row[i]) {
R.clear();
C.clear();
dfs(i, true);
for (int r : R)
for (int c : C)
if (G[r][c] != '#')
y = false;
}
io.println(y ? "Yes" : "No");
io.close();
}
}
class IO{
private BufferedReader br;
private StringTokenizer st;
private PrintWriter writer;
private String inputFile,outputFile;
public boolean hasMore() throws IOException{
if(st != null && st.hasMoreTokens()) return true;
if(br != null && br.ready()) return true;
return false;
}
public String getNext() throws FileNotFoundException, IOException{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String getNextLine() throws FileNotFoundException, IOException{
return br.readLine().trim();
}
public int getNextInt() throws FileNotFoundException, IOException{
return Integer.parseInt(getNext());
}
public long getNextLong() throws FileNotFoundException, IOException{
return Long.parseLong(getNext());
}
public void print(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f" ,x);
}
public void println(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f\n" ,x);
}
public void print(Object o) throws IOException{
writer.print(o.toString());
}
public void println(Object o) throws IOException{
writer.println(o.toString());
}
public IO(String x,String y) throws FileNotFoundException, IOException{
inputFile = x;
outputFile = y;
if(x != null) br = new BufferedReader(new FileReader(inputFile));
else br = new BufferedReader(new InputStreamReader(System.in));
if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
else writer = new PrintWriter(new OutputStreamWriter(System.out));
}
protected void close() throws IOException{
br.close();
writer.close();
}
public void outputArr(Object [] A) throws IOException{
int L = A.length;
for (int i = 0;i < L;i++) {
if(i > 0) writer.print(" ");
writer.print(A[i]);
}
writer.print("\n");
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 38ca9d40f73f3d33254ab6205a31008d | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf2
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int arr[][]=new int[n][m];
for(int i = 0 ;i<n;i++)
{
String s=sc.next();
for(int j=0;j<m;j++)
arr[i][j]=s.charAt(j);
}
int rowmark[]=new int[n];
int columnmark[]=new int[m];
for(int i =0;i<n;i++)
{
if(rowmark[i]==1)
continue;
int rows[]=new int[200];
int columns[]=new int[200];
int rcount=0;
int ccount=0;
for(int j=0;j<m;j++)
{
if(arr[i][j]=='#')
{
if(columnmark[j]==1)
{
System.out.println("No");
System.exit(0);
}
columns[ccount++]=j;
columnmark[j]=1;
}
}
for(int j=0;j<ccount;j++)
{
int val=columns[j];
for(int k=0;k<n;k++)
{
if(rowmark[k]!=1)
{
if(arr[k][val]=='#')
{
rows[rcount++]=k;
rowmark[k]=1;
}
}
}
}
for(int j= 0 ;j<rcount;j++)
{
for(int k=0;k<ccount;k++)
{
int val1=rows[j];
int val2=columns[k];
if(arr[val1][val2]=='.')
{
System.out.println("No");
System.exit(0);
}
}
}
for(int j= 0 ;j<rcount;j++)
{
for(int k=0;k<ccount;k++)
{
int val1=rows[j];
int val2=columns[k];
arr[val1][val2]='.';
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(arr[i][j]=='#')
{
System.out.println("No");
System.exit(0);
}
}
}
System.out.println("YES");
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | b523bde9e12ebe2003de8b10701563c8 | train_000.jsonl | 1521905700 | There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long maxl = (long) 4e18, mod = (long)1e9 + 7L;
void solve(){
//Enter code here utkarsh
int n = ni();
int m = ni();
char[][] s = new char[n][m];
int cnt = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
s[i][j] = nc();
if(s[i][j] == '#') cnt++;
}
}
boolean row[] = new boolean[n];
boolean col[] = new boolean[m];
for(int i = 0; i < n; i++) {
if(row[i]) continue;
row[i] = true;
for(int j = 0; j < m; j++) {
if(col[j]) continue;
if(s[i][j] == '#') {
for(int k = i+1; k < n; k++) {
if(s[k][j] == '#') {
for(int jj = 0; jj < m; jj++) {
if(s[i][jj] != s[k][jj]) {
out.println("No");
return;
}
if(s[k][jj] == '#') cnt--;
}
row[k] = true;
}
}
for(int jj = 0; jj < m; jj++) {
if(s[i][jj] == '#') {
cnt--;
if(col[jj]) {
out.println("No");
return;
}
col[jj] = true;
}
}
break;
}
}
}
if(cnt == 0) out.println("Yes");
else out.println("No");
}
long modpow(long base, long exp, long modulus) { base %= modulus; long result = 1L; while (exp > 0) { if ((exp & 1)==1) result = (result * base) % modulus; base = (base * base) % modulus; exp >>= 1; } return result;
}
public static void main(String[] args) { new utkarsh().run();
}
void run(){ is = System.in; out = new PrintWriter(System.out); solve(); out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte(){ if(ptr >= len){ ptr = 0; try{ len = is.read(input); }catch(IOException e){ throw new InputMismatchException(); } if(len <= 0){ return -1; } } return input[ptr++];
}
boolean isSpaceChar(int c){ return !( c >= 33 && c <= 126 );
}
int skip(){ int b = readByte(); while(b != -1 && isSpaceChar(b)){ b = readByte(); } return b;
}
char nc(){ return (char)skip();
}
String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString();
}
int ni(){ int n = 0,b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } if(b == -1){ return -1; } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n;
}
long nl(){ long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n;
}
double nd(){ return Double.parseDouble(ns());
}
float nf(){ return Float.parseFloat(ns());
}
int[] na(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++){ a[i] = ni(); } return a;
}
char[] ns(int n){ char c[] = new char[n]; int i,b = skip(); for(i = 0; i < n; i++){ if(isSpaceChar(b)){ break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i);
}
} | Java | ["5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..", "5 5\n..#..\n..#..\n#####\n..#..\n..#..", "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#"] | 1 second | ["Yes", "No", "No"] | NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Java 8 | standard input | [
"implementation",
"greedy"
] | ac718922461f3187d8b7587c360b05fc | The first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup. | 1,300 | If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower). | standard output | |
PASSED | 2997bc0592b229700d2cfb1894404277 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
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) {
String line = in.nextLine();
String[] tokens = line.split(" ");
int id = -1;
if (tokens.length == 1) {
String s = tokens[0];
if (s.endsWith("etr") || s.endsWith("etra") || s.endsWith("liala") || s.endsWith("lios") || s.endsWith("inites") || s.endsWith("initis")) {
out.println("YES");
} else {
out.println("NO");
}
return;
}
for (int i = 0; i < tokens.length; ++i) {
if (tokens[i].endsWith("etr") || tokens[i].endsWith("etra")) {
if (id != -1) {
out.println("NO");
return;
}
id = i;
}
}
if (id == -1) {
out.println("NO");
return;
}
boolean fem = true;
if (tokens[id].endsWith("etr")) {
fem = false;
}
for (int i = 0; i < id; ++i) {
if (fem) {
if (!tokens[i].endsWith("liala")) {
out.println("NO");
return;
}
} else {
if (!tokens[i].endsWith("lios")) {
out.println("NO");
return;
}
}
}
for (int i = id + 1; i < tokens.length; ++i) {
if (fem) {
if (!tokens[i].endsWith("inites")) {
out.println("NO");
return;
}
} else {
if (!tokens[i].endsWith("initis")) {
out.println("NO");
return;
}
}
}
out.println("YES");
}
}
class InputReader {
private BufferedReader reader;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | ad6b05f8fd7bf355180c1169728f097b | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.util.Scanner;
public class One113A {
public static void main(String args[]) {
String str = new Scanner(System.in).nextLine();
String words[] = str.split(" ");
String text[] = {(".*lios"), (".*liala"), (".*etr"),
(".*etra"), (".*initis"), (".*inites")};
boolean bool = true;
for(int i=0; i<words.length; i++) {
//check if language
if(!(words[i].matches(text[0]) || words[i].matches(text[1]) ||
words[i].matches(text[2]) || words[i].matches(text[3]) ||
words[i].matches(text[4]) || words[i].matches(text[5])
)) {
bool = false;
break;
//check if one word
} else if(words.length==1) {
break;
} else if(i!=words.length-1) {
// check if no verbs
if(words[words.length-1].matches(text[0]) || words[words.length-1].matches(text[1]) ||
words[0].matches(text[4]) || words[0].matches(text[5])) {
bool = false;
break;
}
//check if male
if(words[i].matches(text[0])) {
if(!(words[i+1].matches(text[0]) || words[i+1].matches(text[2]))) {
bool = false;
break;
}
} else if(words[i].matches(text[2])) {
if(!(words[i+1].matches(text[4]))) {
bool = false;
break;
}
} else if(words[i].matches(text[4])) {
if(!(words[i+1].matches(text[4]))) {
bool = false;
break;
}
}
//check if female
if(words[i].matches(text[1])) {
if(!(words[i+1].matches(text[1]) || words[i+1].matches(text[3]))) {
bool = false;
break;
}
} else if(words[i].matches(text[3])) {
if(!(words[i+1].matches(text[5]))) {
bool = false;
break;
}
} else if(words[i].matches(text[5])) {
if(!(words[i+1].matches(text[5]))) {
bool = false;
break;
}
}
}
}
System.out.println(bool==true? "YES" : "NO");
}
} | Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 47dc994b66fa212cbbcc328f052f6f45 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.util.Scanner;
import java.util.StringTokenizer;
public class GrammarLessons {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
s = s.replaceAll("\\b[a-z]*lios\\b", "_A");
s = s.replaceAll("\\b[a-z]*liala\\b", "_a");
s = s.replaceAll("\\b[a-z]*etr\\b", "_N");
s = s.replaceAll("\\b[a-z]*etra\\b", "_n");
s = s.replaceAll("\\b[a-z]*initis\\b", "_V");
s = s.replaceAll("\\b[a-z]*inites\\b", "_v");
s = s.replaceAll("\\s", "");
if (!s.startsWith("_") || s.matches(".*[A-Za-z]{2}.*")){
System.out.println("NO");
System.exit(0);
}
s = s.replaceAll("\\_", "");
if (s.length() == 1 || s.matches("a*nv*") || s.matches("A*NV*")) System.out.println("YES");
else {
System.out.println("NO");
System.exit(0);
}
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 2f450e98337bb74df92bdb6c0a502543 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class A113
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static boolean endswith(String s1,String s2)
{
if(s1.length()<s2.length())
return false;
for(int i=s1.length()-1,j=s2.length()-1;i>=0&&j>=0;i--,j--)
{
if(s1.charAt(i)!=s2.charAt(j))
return false;
}
return true;
}
public static void main(String[] args)
{
String s=in.nextLine();
String[] words=s.split(" ");
if(words.length==1)
{
if(endswith(s, "lios")||endswith(s, "etr")||endswith(s, "initis")||endswith(s, "liala")||endswith(s, "etra")||endswith(s, "inites"))
{
System.out.println("YES");
return;
}
System.out.println("NO");
return;
}
else
{
boolean male=false;
boolean female=false;
boolean adj=false;
boolean noun=false;
boolean verb=false;
int cnt=0;
for(int i=0;i<words.length;i++)
{
if(male && female)
{
System.out.println("NO");
return;
}
if(!noun && verb)
{
System.out.println("NO");
return;
}
boolean curmale=false;
boolean curfemale=false;
if(endswith(words[i], "lios")||endswith(words[i], "etr")||endswith(words[i], "initis"))
{
male=true;
curmale=true;
}
if(endswith(words[i], "liala")||endswith(words[i], "etra")||endswith(words[i], "inites"))
{
female=true;
curfemale=true;
}
if(!curmale && !curfemale)
{
System.out.println("NO");
return;
}
if(male&&female)
{
System.out.println("NO");
return;
}
int cursit=0;
if(endswith(words[i], "lios")||endswith(words[i], "liala"))
cursit=1;
if(endswith(words[i], "etr")||endswith(words[i], "etra"))
{
cursit=2;
noun=true;
cnt++;
}
if(endswith(words[i], "initis")||endswith(words[i], "inites"))
{
cursit=3;
verb=true;
}
if(cursit==0 || cnt>1 ||(noun&&cursit==1)||(!noun&&cursit==3))
{
System.out.println("NO");
return;
}
}
if(!noun)
{
System.out.println("NO");
return;
}
out.println("YES");
}
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
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 long nextLong()
{
return Long.parseLong(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;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
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 print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 5a40ac23e040fc1303cb38bf6d1ef717 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.util.Scanner;
public class Grammar_Lessons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] statement = sc.nextLine().split(" ");
String ans;
if(isMasculine(statement[0]))
ans = isstatment(statement,0);
else
ans = isstatment(statement,1);
System.out.println(ans);
}
public static boolean isMasculine(String str){
if( (endwith(str,"lios")||endwith(str,"etr")||endwith(str,"initis")))
return true;
else
return false;
}
public static String isstatment(String[] statement,int sex){
int len = statement.length;
int []sta = new int[len];
int[] part;
for(int i=0;i<len;i++) {
part = parts(statement[i]);
if (part[0]!=sex)
return "NO";
else
sta[i] = part[1];
}
if(len == 1)
return "YES";
int count = 0;
if(sta[0] == 2)
count = 1;
for(int i=1;i<len;i++){
if(sta[i] < sta[i-1])
return "NO";
else if(sta[i] ==2)
count ++;
}
if(count == 1) return "YES";
else return "NO";
}
public static boolean endwith(String s1,String s2){
if ( s2.length() > s1.length())
return false;
else if(s1.lastIndexOf(s2) == (s1.length()-s2.length()))
return true;
else
return false;
}
public static int[] parts(String str){
int[] ans = new int[2];
if(endwith(str,"lios"))
{ans[0] = 0;ans[1] = 1;return ans;}
else if (endwith(str,"liala"))
{ans[0] = 1;ans[1] = 1;return ans;}
else if (endwith(str,"etr"))
{ //System.out.println("etr" + str.lastIndexOf("etr",str.length()));
ans[0] = 0;ans[1] = 2;return ans;}
else if (endwith(str,"etra"))
{ //System.out.println("etr" + str.lastIndexOf("etra",str.length()));
ans[0] = 1;ans[1] = 2;return ans;}
else if (endwith(str,"initis"))
{ans[0] = 0;ans[1] = 3;return ans;}
else if (endwith(str,"inites"))
{ans[0] = 1;ans[1] = 3;return ans;}
else
{ans[0] = 3;ans[1] = -1;return ans;}
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 7fd6887f1ff035e7fd4dbeeb4f1c2b9d | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class P113A {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
static class Task {
private boolean isAdj(String w) {
return w.endsWith("lios") || w.endsWith("liala");
}
private boolean isNoun(String w) {
return w.endsWith("etr") || w.endsWith("etra");
}
private boolean isVerb(String w) {
return w.endsWith("initis") || w.endsWith("inites");
}
private boolean getGender(String w) {
return w.endsWith("lios") || w.endsWith("etr") || w.endsWith("initis");
}
private boolean isValid(String w) {
return isAdj(w) || isNoun(w) || isVerb(w);
}
public void solve(InputReader in, PrintWriter out) {
String line = in.nextLine();
String[] words = line.split(" ");
int i = 0;
int n = words.length;
if (n == 1 && isValid(words[i])) {
out.println("YES");
return;
}
for (; i < n; i++) {
if (!isValid(words[i])) {
out.println("NO");
return;
}
}
i = 0;
boolean gender = getGender(words[0]);
while (i < n && isAdj(words[i]) && gender == getGender(words[i])) {
i++;
}
if (i < n && isNoun(words[i]) && gender == getGender(words[i])) {
i++;
} else {
out.println("NO");
return;
}
while (i < n && isVerb(words[i]) && gender == getGender(words[i])) {
i++;
}
System.out.println(i == n ? "YES" : "NO");
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 5221fc5df124c3f12482b1f711868848 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
//PrintWriter pw = new PrintWriter("output.out", "UTF-8");
tk = new StringTokenizer(in.readLine());
int [] val = new int[tk.countTokens()];
int [] f = new int[7];
for(int i=0; i<val.length; i++) {
String s = tk.nextToken();
if(s.endsWith("lios")) val[i] = 0;
else if(s.endsWith("liala")) val[i] = 1;
else if(s.endsWith("etr")) val[i] = 2;
else if(s.endsWith("etra")) val[i] = 3;
else if(s.endsWith("initis")) val[i] = 4;
else if(s.endsWith("inites")) val[i] = 5;
else val[i] = 6;
f[val[i]]++;
}
if(val.length==1 && f[6]==0) {
System.out.println("YES");
return;
}
if(!((f[0]>=0 && f[2]>=0 && f[4]>=0 && f[1]==0 && f[3]==0 && f[5]==0) || (f[0]==0 && f[2]==0 && f[4]==0 && f[1]>=0 && f[3]>=0 && f[5]>=0))) {
System.out.println("NO");
return;
}
if(f[0]==0 && f[2]==0 && f[4]==0) {
f[0] = f[1];
f[2] = f[3];
f[4] = f[5];
for(int i=0; i<val.length; i++) {
if(val[i]==1) val[i]=0;
else if(val[i]==3) val[i]=2;
else if(val[i]==5) val[i]=4;
}
}
if(f[6]>0 || f[2]!=1) {
System.out.println("NO");
return;
}
int i=0;
int [] f2 = new int[7];
while(i<val.length && val[i]==0) {
f2[0]++;
i++;
}
if(i<val.length && val[i]==4) {
System.out.println("NO");
return;
}
while(i<val.length && val[i]==2) {
f2[2]++;
i++;
}
while(i<val.length && val[i]==4) {
f2[4]++;
i++;
}
if(f2[0]==f[0] && f2[2]==f[2] && f2[4]==f[4])
System.out.println("YES");
else System.out.println("NO");
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | f8334c151d531cb5b74d26127bb566ad | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes |
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
@SuppressWarnings("unused")
public class Grammar113A {
InputStream is;
PrintWriter out;
String INPUT = "";
int mod = (int)(Math.pow(10,9)+7);
void solve() {
String s = ns();
StringTokenizer obj = new StringTokenizer(s , " ");
int m = 0 , f = 0;
int adj = 0 , n = 0 , v = 0;
int prev = -1;
int ct = 0;
while(obj.hasMoreTokens()) {
String k = obj.nextToken();
int len = k.length();
boolean r = true;
//out.println(k.substring(len-3, len));
//out.println(k);
if((len >= 4 && k.substring(len-4, len).equals("lios")) ||
(len >= 3 && k.substring(len-3, len).equals("etr")) ||
(len >= 6 && k.substring(len-6, len).equals("initis")) )
m++;
else r = false;
if((len >= 5 && k.substring(len-5, len).equals("liala")) ||
(len >= 4 && k.substring(len-4, len).equals("etra")) ||
(len >= 6 && k.substring(len-6, len).equals("inites")) ) {
f++;
r = true;
}
else if(m==0) r = false;
//out.println(r);
if(!r) {
out.println("NO");
return;
}
if(m != 0 && f != 0) {
out.println("NO");
return;
}
if(m != 0) {
if(len >= 4 && k.substring(len-4, len).equals("lios")) {
if(prev != -1 && prev != 1 && ct!=0) {
out.println("NO");
return;
}
else {
adj++;
prev = 1;
}
}
if(len >= 3 && k.substring(len-3, len).equals("etr")) {
if((prev != 1 || n == 1) && ct != 0) {
out.println("NO");
return;
}
else {
n++;
prev = 2;
}
}
if(len >= 6 && k.substring(len-6, len).equals("initis")) {
if(prev != 2 && prev != 3 && ct != 0) {
out.println("NO");
return;
}
else {
if(ct == 1 && prev != 2) {
out.println("NO");
return;
}
else {
v++;
prev = 3;
}
}
}
}
else {
if(len >= 5 && k.substring(len-5, len).equals("liala")) {
if(prev != -1 && prev != 1 && ct!= 0) {
out.println("NO");
return;
}
else {
adj++;
prev = 1;
}
}
if(len >= 4 && k.substring(len-4, len).equals("etra")) {
//out.println(k+" "+prev+" "+n+" "+ct);
if((prev != 1 || n == 1) && ct!= 0) {
out.println("NO");
return;
}
else {
n++;
prev = 2;
}
}
if(len >= 6 && k.substring(len-6, len).equals("inites")) {
if(prev != 2 && prev != 3 && ct != 0) {
out.println("NO");
return;
}
else {
if(ct == 1 && prev != 2) {
out.println("NO");
return;
}
else {
v++;
prev = 3;
}
}
}
}
ct++;
}
if(prev == 1 && ct > 1)
out.println("NO");
else out.println("YES");
}
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");
//tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Grammar113A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && 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[][] na(int n , int m)
{
int[][] a = new int[n][m];
for(int i = 0;i < n;i++)
for(int j = 0 ; j<m ; j++) a[i][j] = 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();
}
}
void display2D(int a[][]) {
for(int i[] : a) {
for(int j : i) {
out.print(j+" ");
}
out.println();
}
}
int[][] creategraph(int n , int m) {
int g[][] = new int[n+1][];
int from[] = new int[m];
int to[] = new int[m];
int ct[] = new int[n+1];
for(int i = 0 ; i<m; i++) {
from[i] = ni();
to[i] = ni();
ct[from[i]]++;
ct[to[i]]++;
}
int parent[] = new int[n+1];
for(int i = 0 ; i<n+1 ; i++) g[i] = new int[ct[i]];
for(int i = 0 ; i<m ; i++) {
g[from[i]][--ct[from[i]]] = to[i];
g[to[i]][--ct[to[i]]] = from[i];
}
return g;
}
static long __gcd(long a, long b)
{
if(b == 0)
{
return a;
}
else
{
return __gcd(b, a % b);
}
}
// To compute x^y under modulo m
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Function to find modular
// inverse of a under modulo m
// Assumption: m is prime
static long modInverse(long a, int m)
{
if (__gcd(a, m) != 1) {
//System.out.print("Inverse doesn't exist");
return -1;
}
else {
// If a and m are relatively prime, then
// modulo inverse is a^(m-2) mode m
// System.out.println("Modular multiplicative inverse is "
// +power(a, m - 2, m));
return power(a, m - 2, m);
}
}
static long nCrModPFermat(int n, int r,
int p , long fac[])
{
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long t = (fac[n]* modInverse(fac[r], p))%p;
return ( (t* modInverse(fac[n-r], p))% p);
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | e1c7ecb8d192c007fd89b4046b75eb88 | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.nextLine();
ArrayList<word> words = new ArrayList<>();
for (String cur : s.split(" ")) {
words.add(new word(cur));
}
for (word w : words) {
if (w.gender != words.get(0).gender || w.gender == 0 || w.part == 0) {
out.println("NO");
return;
}
}
int nCount = 0;
int aCount = 0;
int vCount = 0;
if (words.size() == 1) {
out.println("YES");
return;
}
for (word w : words) {
if (w.part == 'n') nCount++;
if (nCount == 0) {
if (w.part == 'a') aCount++;
}
if (nCount != 0) {
if (w.part == 'v') vCount++;
}
}
if (nCount != 1) {
out.println("NO");
return;
}
if (aCount + nCount + vCount != words.size()) {
out.println("NO");
return;
}
out.println("YES");
}
class word {
char gender = 0;
char part = 0;
String raw;
word(String raw1) {
raw = raw1;
if (tail("lios")) {
part = 'a';
gender = 'm';
}
if (tail("liala")) {
part = 'a';
gender = 'f';
}
if (tail("etr")) {
part = 'n';
gender = 'm';
}
if (tail("etra")) {
part = 'n';
gender = 'f';
}
if (tail("initis")) {
part = 'v';
gender = 'm';
}
if (tail("inites")) {
part = 'v';
gender = 'f';
}
}
boolean tail(String t) {
if (raw.length() < t.length()) return false;
return raw.substring(raw.length() - t.length(), raw.length()).equals(t);
}
}
}
static class InputReader {
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | 8d99170d4955ec46c7558db232490b8b | train_000.jsonl | 1315494000 | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. | 256 megabytes | import java.util.*;
public class GrammarLessons{
static class Parte{
public int tipo; // 0- Desconocido, 1- Adjetivo, 2- Sustantivo, 3- Verbo
public int genero; // 0- Desconocido, 1- Masculino, 2- Femenino
}
private static String[] sufijos;
public static void main(String args[]){
sufijos = new String[]{"lios", "liala", "etr", "etra", "initis", "inites"};
Scanner sc = new Scanner(System.in);
LinkedList<String> palabras = new LinkedList<>();
while(sc.hasNext()){
String palabra = sc.next();
palabras.add(palabra);
}
if(palabras.size() == 1){
Parte p = getParte(palabras.get(0));
if(p != null){
System.out.println("YES");
}else{
System.out.println("NO");
}
}else{
String palabra = palabras.get(0);
Parte p = getParte(palabra);
if(p != null){
int tipo = p.tipo;
boolean sustantivo = tipo == 2;
if(tipo == 3){
// Error: verbo antes de sustantivo.
System.out.println("NO");
return;
}
int generoFrase = p.genero;
int i = 1;
for(i = 1; i < palabras.size(); i++){
palabra = palabras.get(i);
p = getParte(palabra);
if(p == null){
// NO!
System.out.println("NO");
return;
}else{
if(p.genero == generoFrase){
if(!sustantivo && p.tipo == 2){
sustantivo = true;
}else if(!sustantivo && p.tipo == 3){
System.out.println("NO");
return;
}else if(sustantivo && p.tipo == 1){
System.out.println("NO");
return;
}else if(sustantivo && p.tipo == 2){
System.out.println("NO");
return;
}
}else{
System.out.println("NO");
return;
}
}
}
if(i == palabras.size() && sustantivo){
System.out.println("YES");
}else if(i == palabras.size() && !sustantivo){
System.out.println("NO");
}
}else{
System.out.println("NO");
}
}
}
public static Parte getParte(String palabra){
for(int k = 0; k < sufijos.length; k++){
String sufijo = sufijos[k];
if(palabra.length() >= sufijo.length()){
boolean ok = true;
int i = palabra.length() - 1;
int j = sufijo.length() - 1;
int hasta = palabra.length() - sufijo.length();
while(i >= hasta && ok){
char c1 = palabra.charAt(i);
char c2 = sufijo.charAt(j);
ok = c1 == c2;
i--;
j--;
}
if(ok){
// Sufijo encontrado!
Parte p = new Parte();
p.tipo = (k / 2) + 1;
p.genero = (k % 2 == 0)? 1 : 2;
return p;
}
}
}
return null;
}
} | Java | ["petr", "etis atis animatis etis atis amatis", "nataliala kataliala vetra feinites"] | 5 seconds | ["YES", "NO", "YES"] | null | Java 8 | standard input | [
"implementation",
"strings"
] | 0c9550a09f84de6bed529d007ccb4ae8 | The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. | 1,600 | If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). | standard output | |
PASSED | f9f3cacf7cd58670f4e130ca8d00bde6 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedInputStream;
import java.util.Scanner;
public class _59B
{
public static void main(String[] args)
{
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[k+1];
for(int i=0;i<n;i++)
{
int x = sc.nextInt();
a[x]++;
}
int nbCoins = 0;
while(a[k] < n)
{
for(int i=k-1;i>0;i--)
{
if(a[i] > 0)
{
a[i]--;
a[i+1]++;
}
}
nbCoins++;
}
System.out.println(nbCoins);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 0e4a84355d18aa357c285baa26516f63 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
*
* @author mohamed elshenawy
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader in = new BufferedReader(new FileReader("x.in"));
a: while(in.ready()){
StringTokenizer s=new StringTokenizer(in.readLine());
int n=Integer.parseInt(s.nextToken());
int m=Integer.parseInt(s.nextToken());
StringTokenizer s1=new StringTokenizer(in.readLine());
int a[]=new int[s1.countTokens()];
for (int i = 0; i < a.length; i++) {
a[i]=Integer.parseInt(s1.nextToken());
}
Arrays.sort(a);
int h=0;
int c=0;
int y=a[0];
while (a[0]< m) {c++; int l=-1;
for (int i = 0; i < a.length; i++) {
if(a[i]<m&&a[i]>l){
l=a[i];
a[i]++;
}
}
Arrays.sort(a);
}
System.out.println(c);
}
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | c62892ceeddf9004aab2b356795dc509 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | //package Div2_59;
import java.util.Arrays;
import java.util.Scanner;
public class B {
/**
* @param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int [] a = new int [n];
int c = 0;
for (int i = 0; i < a.length; i++)
a [i] = s.nextInt();
boolean done = false;
while (!done)
{
// System.out.println(Arrays.toString(a));
done = true;
int i;
for (i = 0; i < a.length-1; i++) {
if (a[i] == k) continue;
if (a[i] != k) done = false;
if (a[i] != a[i+1]) a[i]++;
}
if (a[i] != k){
done = false;
a[i]++;
}
c++;
}
System.out.println(c-1);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 93df3f4c14d774f543371de2c11dd05e | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Trung Pham
*/
public class A {
public static void main(String[] args) {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
// System.out.println(k);
int[] count = new int[k];
for (int i = 0; i < n; i++) {
int a = in.nextInt() - 1;
if (a == k - 1) {
break;
}
count[a]++;
}
int result = 0;
for (;;) {
boolean found = false;
int[] temp = new int[k];
for (int i = 0; i < k - 1; i++) {
if (count[i] > 0) {
found = true;
temp[i] += count[i] - 1;
temp[i + 1] += 1;
}
}
if (!found) {
break;
}
result++;
count = temp;
}
out.println(result);
out.close();
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static int pow(int a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
int val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * val * a;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
static Point add(Point a, Point b) {
return new Point(a.x + b.x, a.y + b.y);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point: " + x + " " + y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
}
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 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 842f1ed2f4cfb91848b8d3603421efb7 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] argv) throws IOException{
new Main().run();
}
PrintWriter pw;
Scanner sc;
public void run() throws IOException{
boolean oj = true;//System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
sc = new Scanner(reader);
pw = new PrintWriter(writer);
int n = sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
int tt = 0;
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
if(arr[i]==k) tt++;
}
if(tt==n){
pw.print(0);
pw.close();
return;
}
int ans = 0 ;
while(true){
int temp[] = new int[k];
tt = 0;
for(int i=0;i<n;i++){
if(arr[i]==k){
tt++;
}else
if(temp[arr[i]]==0){
temp[arr[i]]++;
arr[i]++;
}
}
ans++;
if(tt==n) break;
}
pw.println(ans-1);
pw.close();
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | a3e791016ce4733debacea31d744f9c1 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.util.Scanner;
/**
* @author manu
*
*/
public class SettlersTraining {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N, K;
N = in.nextInt();
K = in.nextInt();
int counter = 0;
int a[] = new int[N];
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
}
while (true) {
if (checkState(a, K))
break;
for (int i = 0; i < a.length; i++) {
while (i != N - 1 && a[i] == a[i + 1])
i++;
if (a[i] != K)
a[i] += 1;
}
counter += 1;
}
System.out.println(counter);
}
private static boolean checkState(int[] a, int k) {
for (int i = 0; i < a.length; i++) {
if (a[i] != k)
return false;
}
return true;
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | aadf0ee0dc71c6ae406b4d9336304b03 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.*;
public class straining{
public static void main(String[] args){
Scanner br = new Scanner(System.in);
int n = br.nextInt();
int k = br.nextInt();
int[] nums = new int[k];
int[] temp = new int[k];
for(int i = 0;i<n;i++){
int c = br.nextInt()-1;
nums[c]++;
temp[c]++;
}
int count = 0;
while(nums[k-1] != n){
count++;
for(int i = 0;i<k-1;i++){
if(nums[i] > 0){
nums[i]--;
temp[i]--;
temp[i+1]++;
}
}
for(int i = 0;i<k;i++){
nums[i] = temp[i];
}
}
System.out.println(count);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | f6834b6ff31656e8b4d4b0ee4ec63177 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n,i,k,temp=0;
n=in.nextInt();
k=in.nextInt();
int[] fl =new int[n+1];
for (i=0;i<n;i++)
fl[i]=in.nextInt();
int ans=0;
//Arrays.sort(fl);
fl[n]=k;
while(true)
{ if(fl[0]==k)break;
ans++;
for (i=0;i<n;i++){
if((fl[i]!=fl[i+1]))fl[i]=fl[i]+1;}
}
System.out.print(ans);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 66cd8b1b4d41d08fbd0e5a1768288acc | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class test
{
public static void main(String[] args)
{
new test().run();
}
void run()
{
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
int[] count = new int[k];
int total = 0;
for (int i = 0; i < n; i++)
{
int t = in.nextInt();
if (t == k)
total++;
else
count[t]++;
}
int coin = 0;
while (total < n)
{
for (int i = k - 1; i >= 0; i--)
{
if (i == k - 1 && count[i] > 0)
{
count[i]--;
total++;
}
else
{
if (count[i] > 0)
{
count[i]--;
count[i + 1]++;
}
}
}
coin++;
}
out.println(coin);
out.close();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 4d5082f994d49d9bc858a2901d4067f2 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Round_59 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String[] s = r.readLine().split(" ");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
int[] numbers = new int[x];
int[] finalarr = new int[x];
String[] a = r.readLine().split(" ");
for (int i = 0; i < x; i++) {
numbers[i] = Integer.parseInt(a[i]);
}
int count = 0;
if (numbers.length == 1)
System.out.println(y - numbers[0]);
else {
while (numbers[0] != y) {
Arrays.sort(numbers);
if (numbers[numbers.length - 1] != y) {
finalarr[finalarr.length - 1] = numbers[numbers.length - 1] + 1;
} else {
finalarr[finalarr.length - 1] = numbers[numbers.length - 1];
}
for (int i = numbers.length - 2; i >= 0; i--) {
if (numbers[i] != numbers[i + 1]) {
finalarr[i] = numbers[i] + 1;
} else {
finalarr[i] = numbers[i];
}
}
System.arraycopy(finalarr, 0, numbers, 0, finalarr.length);
count++;
}
System.out.println(count);
}
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 983231034ea997070f48d05761c62b7d | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
int k = nextInt();
int[] am = new int[k + 1];
for (int i = 0; i < n; i++) {
int rank = nextInt();
++am[rank];
}
int res = 0;
while (am[k] < n) {
++res;
for (int i = k - 1; i >= 0; i--)
if (am[i] > 0) {
++am[i + 1];
--am[i];
}
}
out.print(res);
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 78bac910aad263dc4a4c35b43ccfd8d9 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
StreamTokenizer in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new Solution().run();
}
public void run() throws Exception {
in = new StreamTokenizer (new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
String next() throws Exception {
in.nextToken();
return in.sval;
}
public void solve() throws Exception {
int n=nextInt();
int k=nextInt();
int [] a =new int [n];
for (int i=0; i<n;i++)
a[i]=nextInt();
int ans=0;
while (a[0]!=k)
{
int i=0;
while (i<n-1)
{
if (a[i]!=a[i+1]) a[i]++;
i++;
}
if (a[n-1]!=k) a[n-1]++;
ans++;
}
out.println(ans);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 61f02c8d41e92b21e314dc0264ade18d | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class B {
public void run() throws IOException{
Scanner s = new Scanner(new InputStreamReader(System.in));
int n = s.nextInt();
int k = s.nextInt();
int[] r = new int[n];
for (int i = 0; i < r.length; i++) {
r[i] = s.nextInt();
}
int c = 0;
int last;
int count = 0;
boolean l;
while (true){
c = 0;
last = r[0];
l = false;
for (int i = 0; i < r.length; i++) {
if (r[i] != last){
if (r[i-1] < k){
r[i-1]++;
c++;
}
last = r[i];
}
}
if (r[n-1] < k){
r[n-1]++;
c++;
}
// for (int i = 0; i < r.length; i++) {
// System.out.print(r[i]);
// }
// System.out.println();
if (c == 0) break;
count++;
}
System.out.println(count);
}
public static void main(String[] args) throws IOException{
(new B()).run();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | f682d6a4812b8d3c21440365eb7be3bf | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class B {
public void run() throws IOException{
Scanner s = new Scanner(new InputStreamReader(System.in));
int n = s.nextInt();
int k = s.nextInt();
int[] r = new int[n];
for (int i = 0; i < r.length; i++) {
r[i] = s.nextInt();
}
int c = 0;
int last;
int count = 0;
boolean l;
while (true){
c = 0;
last = r[0];
l = false;
for (int i = 0; i < r.length; i++) {
if (r[i] != last){
if (r[i-1] < k){
r[i-1]++;
c++;
}
last = r[i];
}
}
if (r[n-1] < k){
r[n-1]++;
c++;
}
// for (int i = 0; i < r.length; i++) {
// System.out.print(r[i]);
// }
// System.out.println();
if (c == 0) break;
count++;
}
System.out.println(count);
}
public static void main(String[] args) throws IOException{
(new B()).run();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 6479cd161fa470e6fe75ae7dfbe18d83 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
new Main().run();
}
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException
{
in.nextToken();
return (int)in.nval;
}
void run() throws IOException
{
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
void solve() throws IOException
{
int a = nextInt();
int b = nextInt();
int mas[]= new int[a];
for (int i=0; i<a; i++){
mas[i]=nextInt();
}
int mas1[][] = new int[b][2];
for (int i=0; i<a; i++){
mas1[mas[i]-1][0]+=1;
}
// for (int i=0; i<b; i++){
// out.print(mas1[i][0]);
// out.print("------");
// }
int j,o;
j=0;
int k=0;
while (mas1[b-1][j]!=a){
k++;
if ((k%2)==1){j=1; o=0;}else {j=0;o=1;}
for (int i=0; i<b; i++){
mas1[i][j]=0;
}
for (int i=0; i<(b-1); i++){
if (mas1[i][o]!=0){
mas1[i][j]+= mas1[i][o]-1;
// mas1[i][j]=mas1[i][o]-1;
mas1[i+1][j]=1;
}
}
mas1[b-1][j]+= mas1[b-1][o];
}
out.println(k);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 80920bb3fb4b2f4a96478dbfada81a08 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
private static StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
private static PrintWriter out = new PrintWriter(System.out);
private static int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
private static String nextString() throws Exception {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws Exception {
int n = nextInt(), k = nextInt();
int[] a = new int[k + 1], b = new int[k + 1];
for (int i = 0; i < n; i++) {
a[nextInt()]++;
}
int p = 0;
while (a[k] != n) {
b = a.clone();
for (int i = 0; i < k; i++) {
if (a[k] == n) {
break;
}
if (a[i] > 0) {
b[i]--;
b[i + 1]++;
}
}
a = b;
p++;
}
out.println(p);
out.flush();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 49c405187c09bd4d802ec130b8b130f9 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solution{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n, k;
n = in.nextInt();
k = in.nextInt();
int a[] = new int[n+1];
int ind[] = new int[k+1];
for(int i=0; i<=k; i++){
ind[i] = 0;
}
for(int i=1;i<=n; i++){
a[i] = in.nextInt();
ind[a[i]]++;
}
int sum = 0;
for(int i=1; i<=n*k; i++){
boolean isEnd = false;
if(ind[k] == n)
isEnd = true;
if(isEnd)
break;
for(int j=k; j>0; j--){
if(ind[j-1]>0){
ind[j]++;
ind[j-1]--;
}
}
sum++;
}
out.println(sum);
out.flush();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 19035d15ad36c667e12cd2dc98578c77 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author lazarov
*/
public class codeforces592 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int drank = scan.nextInt();
int so[] = new int[num+1];
for (int i = 0; i < so.length-1; i++) {
so[i] = scan.nextInt();
}
so[num]=drank;
int ret=0;
while(!check(so,drank)){
for (int i = 1; i < so.length&&so[i]<=drank; i++) {
if(so[i]!=so[i-1]){
so[i-1]++;
}
}
ret++;
}
System.out.println(ret);
}
public static boolean check(int []s,int r){
for (int i = 0; i < s.length; i++) {
if(s[i]!=r)return false;
}
return true;
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | cef8ecac10030ede195a7b22f6cd5f52 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
InputStream fin = System.in;
//fin = new FileInputStream("in.txt");
Scanner cin = new Scanner(fin);
int[] rank;
while (cin.hasNext()) {
int n = cin.nextInt();
int k = cin.nextInt();
int ret = 0;
rank = new int[n];
for (int i = 0; i < n; i++) {
rank[i] = cin.nextInt();
}
while (true) {
boolean fail = true;
LinkedList[] list = new LinkedList[k];
for (int i = 0; i < k; i++) {
list[i] = new LinkedList<Integer>();
}
for (int i = 0; i < n; i++) {
if (rank[i] < k) {
list[rank[i]].add(i);
fail = false;
}
}
if (fail)
break;
for (int i = 0; i < k; i++) {
if (!list[i].isEmpty()) {
rank[(Integer) list[i].get(0)]++;
}
}
ret++;
}
System.out.println(ret);
}
fin.close();
cin.close();
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 9eff83b2c5410f3cf56e3384803cc0bb | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.util.Scanner;
/**
*
* @author epiZend
*/
public class TheSettlers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int last = k;
int sess = 0;
while (true) {
for (int i = n - 1; i >= 0; i--) {
if (a[i] != last) {
last = a[i];
a[i]++;
}
}
if (last == k) {
System.out.println(sess);
return;
}
sess++;
}
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 97fb4567a7f57fa8bb599879fb83f229 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = sc.nextIntArray(n);
int[] state = new int[k + 1];
int time = 0;
for (; ; ) {
int min = k;
for (int i = 0; i < n; i++) min = min(min, a[i]);
if (min == k) break;
time++;
for (int i = 0; i < n; i++) {
if (a[i] < k && state[a[i]] < time) {
state[a[i]] = time;
a[i]++;
}
}
}
out.println(time);
}
static void tr(Object... os) {
System.err.println(deepToString(os));
}
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 2aa170e893de7dd16454b4143c95d946 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.*;
public class B59 {
static InputStreamReader inp = new InputStreamReader(System.in);
static BufferedReader in = new BufferedReader(inp);
static boolean test = false;
static PrintWriter writer = new PrintWriter(System.out);
static StreamTokenizer inTok = new StreamTokenizer(in);
static String testDataFile = "testdata.txt";
BufferedReader reader = null;
public B59() throws Throwable {
if (test) {
reader = new BufferedReader(new FileReader(new File(testDataFile)));
inTok = new StreamTokenizer(reader);
}
}
private int in() throws NumberFormatException, IOException {
inTok.nextToken();
return (int) inTok.nval;
}
private double doub() throws NumberFormatException, IOException {
inTok.nextToken();
return (double) inTok.nval;
}
private String str() throws NumberFormatException, IOException {
inTok.nextToken();
return inTok.sval;
}
public String readLine() throws IOException {
if (test) {
return reader.readLine();
} else {
return in.readLine();
}
}
/**
* Entry point
*/
public static void main(String[] args) throws Throwable {
// long t0 = System.currentTimeMillis();
new B59().solve();
// long t1 = System.currentTimeMillis();
// System.out.println("time: " + (t1 - t0));
}
private void solve() throws Throwable {
int n = in();
int k = in();
int[] levels = new int[k];
for (int i = 0; i < n; i++) {
levels[in() - 1] ++;
}
int coin = 0;
while(true){
boolean mod = false;
for (int i = levels.length - 2; i >= 0 ; i--) {
if(levels[i] != 0){
levels[i] --;
levels[i + 1] ++;
mod = true;
}
}
if(!mod){
System.out.println(coin);
return;
}
coin ++;
}
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 6a7292d4c9189c6e88d125d1012a5bdb | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.util.*;
public class TrainsOfSettlers {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] solder = new int[n+1];
solder[n] = 1000;
for(int i = 0; i<n; i++){
solder[i] = in.nextInt();
}
int gold = 0;
while(solder[0] != k){
for(int j = 0; j<n; j++){
if(solder[j] != solder[j+1] && solder[j]<=k){
++solder[j];
}
}
++gold;
}
System.out.println(gold);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | be58ddffc6e7f35e200c98d26ba6023e | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main (String[]ar)throws Exception{
BufferedReader read = new BufferedReader (new InputStreamReader(System.in));
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
StringTokenizer st = new StringTokenizer(read.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
boolean[] up = new boolean[102];
int[] x = new int[n];
st = new StringTokenizer(read.readLine());
for(int i=0;i<n;i++)
x[i] = Integer.parseInt(st.nextToken());
boolean flag = false;
int steps = 0;
while(!flag){
flag = true;
for(int i=0;i < n;i++){
if(!up[x[i]] && x[i] != k){
up[x[i]] = true;
flag = false;
x[i]++;
}
}
steps++;
Arrays.fill(up,false);
}
System.out.println(steps-1);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | abf1ce7b2dadde241986b806a1b1bdde | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Solution63B {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
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());
}
public static void main(String[] args){
new Solution63B().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);
}
}
static class Utils {
private Utils() {}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
void solve() throws IOException{
int n = readInt();
int k = readInt();
int[] a = new int[n + 1];
for(int i = 0; i < n; i++){
a[i] = readInt();
}
a[n] = k;
int count = 0;
while(a[0] != k){
int cur = a[n];
for(int i = n-1; i >= 0; i--)
if(a[i] != k && a[i] < cur){
cur = a[i];
a[i]++;
}
count++;
}
out.println(count);
}
static double distance(long x1, long y1, long x2, long y2){
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long gcd(long a, long b){
while(a != b){
if(a < b) a -=b;
else b -= a;
}
return a;
}
static long lcm(long a, long b){
return a * b /gcd(a, b);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 02afb3e434d7a852ba11ac77897954cc | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int ans=0;
int array[]=new int[k+1];
for( int j = 0; j <n; j++)
array[in.nextInt()]++;
while(array[k]!=n)
{
for(int j = k; j > 1; j--)
if(array[j-1]>0)
{
array[j]++;
array[j-1]--;
}
ans++;
}
System.out.println(ans);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | f64fc33a67e508a157daeee24e58b675 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 2/28/11
* Time: 9:18 PM
* To change this template use File | Settings | File Templates.
*/
public class Task2 {
void run(){
int N = nextInt(), K = nextInt();
int[] num = new int[K];
for(int i = 0; i < N; i++){
int x = nextInt();
num[x - 1]++;
}
boolean possible = false;
for(int i = 0; i < K - 1; i++) if(num[i] > 0) possible = true;
int ans = 0;
while(possible){
int[] temp = Arrays.copyOf(num, num.length);
ans++;
for(int i = 0; i < K - 1; i++){
if(num[i] > 0){
temp[i]--;
temp[i + 1]++;
}
}
num = Arrays.copyOf(temp, temp.length);
possible = false;
for(int i = 0; i < K - 1; i++) if(num[i] > 0) possible = true;
}
System.out.println(ans);
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Task2().run();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | de136f28be341b19463bf96997ac6f90 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 2/28/11
* Time: 9:18 PM
* To change this template use File | Settings | File Templates.
*/
public class Task2 {
void run(){
int N = nextInt(), K = nextInt();
int[] num = new int[K];
for(int i = 0; i < N; i++){
int x = nextInt();
num[x - 1]++;
}
boolean possible = false;
for(int i = 0; i < K - 1; i++) if(num[i] > 0) possible = true;
int ans = 0;
while(possible){
int[] temp = Arrays.copyOf(num, num.length);
ans++;
for(int i = 0; i < K - 1; i++){
if(num[i] > 0){
temp[i]--;
temp[i + 1]++;
}
}
num = Arrays.copyOf(temp, temp.length);
possible = false;
for(int i = 0; i < K - 1; i++) if(num[i] > 0) possible = true;
}
System.out.println(ans);
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Task2().run();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 38faa44f6502c02081fcb11a4d1fef13 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.Scanner;
public class R59d2_63B {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int sum = 0;
int[] ranks = new int[n];
int[] newranks = new int[n];
for (int i = 0; i < n; i++) {
ranks[i] = s.nextInt();
}
while (ranks[0] < k) {
sum++;
int i = 0;
for (; i < n - 1; i++) {
if (ranks[i] >= k)
continue;
if (ranks[i] != ranks[i + 1])
newranks[i] = ranks[i] + 1;
else
newranks[i] = ranks[i];
}
if (ranks[i] < k)
newranks[i] = ranks[i] + 1;
for (i = 0; i < n; i++) {
if (ranks[i] >= k)
break;
ranks[i] = newranks[i];
}
}
System.out.println(sum);
}
}
// Input
// 6 10
// 1 1 3 4 9 9
// Output
// 10
// Input
// 10 13
// 2 6 6 7 9 9 9 10 12 12
// Output
// 11
// Input
// 4 4
// 1 2 2 3
// Output
// 4
// Input
// 4 3
// 1 1 1 1
// Output
// 5
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 385beb0d43b2ba01e548b3e08e7f2470 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.Scanner;
public class p63b {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] all= new int[k+1];
for (int i = 0; i < n; i++) {
all[in.nextInt()]++;
}
int c = 0;
while(true) {
if(all[k] == n)
break;
c++;
for (int i = k-1; i >=0; i--) {
if(all[i]!=0) {
all[i]--;
all[i+1]++;
}
}
}
System.out.println(c);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 6ae7dd67a5f83301091ebc504aa88c20 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringTokenizer;
public class r59_b {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
int n=nextInt(),k=nextInt();
Long a[]=new Long[n+2];
for (int i = 1; i <=n; i++) {
a[i]=nextLong();
}
Arrays.sort(a,1,n+1);
int ans=0,l=n;
for (int i = 1; i <=1000; i++) {
while(l>0&&a[l]==k)
l--;
if(l<=0)
break;
ans++;
//Arrays.sort(a,1,l+1);
for (int j = 1; j <=l; j++) {
if(a[j]!=a[j+1])
a[j]++;
}
// for (int j =1; j <=n; j++) {
// pw.print(a[j]+" ");
// }
// pw.println();
}
pw.print(ans);
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | cd53bfe2a0082b93008f6d2b48b49bd7 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
if (n == 1) {
out.print(k - in.nextInt());
} else {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
int ans = 0;
while (true) {
boolean inc = false;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
arr[i - 1]++;
inc = true;
}
if (arr[i] == k)
break;
}
if (arr[n - 1] != k) {
arr[n - 1]++;
inc = true;
}
if (!inc)
break;
else
ans++;
}
out.print(ans);
}
out.close();
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | d5d27b03020123e3c341ac5a15cd88b4 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import static java.lang.Double.*;
import static java.math.BigInteger.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main implements Runnable {
private void solve() throws IOException {
// long start = System.currentTimeMillis();
readData();
processing();
}
private void processing() {
println(res);
}
private void readData() throws IOException {
n = nextInt();
m = nextInt();
int[] s = new int[m+1];
fill(s, 0);
for (int i = 0; i < n; ++i) {
int rang = nextInt();
++s[rang];
}
int old = 0;
int cur = 1;
while (s[m] < n) {
++res;
for (int i = m-1; i > 0; --i) {
if (s[i] > 0) {
--s[i];
++s[i+1];
}
}
cur ^= 1;
old ^= 1;
}
}
private int n;
private int m;
private int res;
public static void main(String[] args) throws InterruptedException {
new Thread(null, new Runnable() {
public void run() {
new Main().run();
}
}, "1", 1 << 24).start();
}
// @Override
public void run() {
try {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
reader = onlineJudge ? new BufferedReader(new InputStreamReader(
System.in)) : new BufferedReader(
new FileReader("input.txt"));
writer = onlineJudge ? new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out))) : new PrintWriter(
new BufferedWriter(new FileWriter("output.txt")));
Locale.setDefault(Locale.US);
tokenizer = null;
solve();
writer.flush();
} catch (Exception error) {
error.printStackTrace();
System.exit(1);
}
}
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer tokenizer;
private void println() {
writer.println();
}
private void print(long value) {
writer.print(value);
}
private void println(long value) {
writer.println(value);
}
private void print(char ch) {
writer.print(ch);
}
private void println(String s) {
writer.println(s);
}
private void print(String s) {
writer.print(s);
}
private void print(int value) {
writer.print(value);
}
private void println(int value) {
writer.println(value);
}
private void printf(String f, double d) {
writer.printf(f, d);
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | a834f6b7fac09852437c8d31e2361776 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Main{
static class Run implements Runnable{
//TODO parameters
final boolean consoleIO = true;
final String inFile = "input.txt";
final String outFile = "output.txt";
@Override
public void run() {
int n = nextInt();
int k = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; ++i)
a[i] = nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
boolean gained;
int c = 0;
do {
gained = false;
for(int i = 0; i < n; ++i) {
if(!hs.contains(a[i]) && a[i] < k) {
hs.add(a[i]);
++a[i];
gained = true;
}
}
hs.clear();
if(gained)
++c;
} while(gained);
print(c);
close();
}
//=========================================================================================================================
BufferedReader in;
PrintWriter out;
StringTokenizer strTok;
Run() {
if (consoleIO) {
initConsoleIO();
}
else {
initFileIO();
}
}
void initConsoleIO() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
void initFileIO() {
try {
in = new BufferedReader(new FileReader(inFile));
out = new PrintWriter(new FileWriter(outFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void close() {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
float nextFloat() {
return Float.parseFloat(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return "__NULL";
}
}
boolean hasMoreTokens() {
return (strTok == null) || (strTok.hasMoreTokens());
}
String nextToken() {
while (strTok == null || !strTok.hasMoreTokens()) {
String line;
try {
line = in.readLine();
strTok = new StringTokenizer(line);
} catch (IOException e) {
e.printStackTrace();
}
}
return strTok.nextToken();
}
void cout(Object o){
System.out.println(o);
}
void print(Object o) {
out.write(o.toString());
}
void println(Object o) {
out.write(o.toString() + '\n');
}
void printf(String format, Object... args) {
out.printf(format, args);
}
String sprintf(String format, Object... args) {
return MessageFormat.format(format, args);
}
}
static class Pair<A, B> {
A a;
B b;
A f() {
return a;
}
B s() {
return b;
}
Pair(A a, B b) {
this.a = a;
this.b = b;
}
Pair(Pair<A, B> p) {
a = p.f();
b = p.s();
}
}
public static void main(String[] args) throws IOException {
Run run = new Run();
Thread thread = new Thread(run);
thread.run();
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | b4a8e8fe6dc84bdda5f09d32ae5dbbfa | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.util.Scanner;
//package b;
public class Main
{
static Scanner sin =new Scanner(System.in);
public static void main(String[] args)
{
int cnt=0,n,k;
int a[]=new int[110];
n=sin.nextInt();
k=sin.nextInt();
a[n]=k;
for(int i=0;i<n;i++) a[i]=sin.nextInt();
while(a[0]<k)
{
cnt++;
for(int i=0;i<n;i++)
{
if(a[i]>=k) break;
else if(a[i]<a[i+1])
a[i]++;
}
}
System.out.println(cnt);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 04ee5d74384ec29d9f2de177766940de | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int N;
int K;
int[] count;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
N = nextInt();
K = nextInt();
count = new int [K + 1];
for (int i = 0; i < N; i++)
count[nextInt()]++;
int ans = 0;
while (count[K] < N) {
for (int i = K - 1; i > 0; i--) {
if (count[i] > 0) {
count[i]--;
count[i + 1]++;
}
}
ans++;
}
out.println(ans);
out.close();
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return true;
}
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 70ed52d38ae220838520abb902bbd529 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.Scanner;
public class SettlerTraining{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int tc = input.nextInt();
int max = input.nextInt();
int[] arr = new int [max];
boolean[] param = new boolean [max];
for(int i = 0; i< tc; i++){
int temp = input.nextInt()-1;
arr[temp] = arr[temp]+1;
}
int ans = 0;
while(arr[max-1] <tc){
for(int i = 0; i<max-1; i++){
if(arr[i] > 0){
arr[i] = arr[i] -1;
param[i+1] = true;
}
else param[i+1] = false;
}
for(int i = 0; i<max; i++){
if(param[i]) arr[i] = arr[i]+1;
}
ans++;
}
System.out.println(ans);
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 0990fa8a3e453fb1b932fe393d226df7 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.*;
public class Train{
public static void main(String args[])throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int i=0,j=0,n=Integer.parseInt(st.nextToken()),k=Integer.parseInt(st.nextToken()),sum=0,n1=n;
int a[]=new int[101],b[]=new int[101];
st=new StringTokenizer(br.readLine());
while(n1-->0){
a[Integer.parseInt(st.nextToken())]++;}
for(i=0;i<=k;i++)
b[i]=a[i];
while(a[k]!=n)
{sum++;
for(i=1;i<=k;i++)
if(i!=k&&a[i]>0)
{a[i]--;
b[i]--;
b[i+1]++;
}
for(i=0;i<=k;i++)
a[i]=b[i];
}
System.out.println(sum);
}} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 9abf34f508e9210f705400a46064be97 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound59_B implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
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());
}
@Override
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);
}
}
public static void main(String[] args) {
new Thread(new BetaRound59_B()).start();
}
void solve() throws IOException {
int n = readInt();
int k = readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
int[] b = new int[k+1];
for (int i = 0; i < n; i++) {
b[a[i]]++;
}
int ans = 0;
int[] c = new int[k+1];
while (b[k] < n) {
for (int i = 1; i < k; i++) {
if (b[i] != 0) c[i + 1]++;
}
for (int i = 1; i <= k; i++) {
if (c[i] != 0) {
b[i - 1]--;
b[i] += c[i];
}
}
ans++;
Arrays.fill(c, 0);
}
out.print(ans);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 83c55cf9feec8262da05206a54cdefee | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound59_B implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
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());
}
@Override
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);
}
}
public static void main(String[] args) {
new Thread(new BetaRound59_B()).start();
}
void solve() throws IOException {
int n = readInt();
int k = readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
int[] b = new int[k+1];
for (int i = 0; i < n; i++) {
b[a[i]]++;
}
int ans = 0;
int[] c = new int[k+1];
while (b[k] < n) {
for (int i = 1; i < k; i++) {
if (b[i] != 0) c[i + 1]++;
}
for (int i = 1; i <= k; i++) {
if (c[i] != 0) {
b[i - 1]--;
b[i] += c[i];
}
}
ans++;
Arrays.fill(c, 0);
}
out.print(ans);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 1d4026511034ebe6039d1ed714712c84 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String args[]) throws Exception
{
Solution sol = new Solution();
sol.Run();
}
static public class Solution
{
void Solve(BufferedReader input, PrintStream output) throws Exception
{
Scanner scanner = new Scanner(input);
int n = scanner.nextInt();
int k = scanner.nextInt();
int levels[] = new int[k + 1];
int cnt = 0;
for (int i = 0; i < n; i++) levels[scanner.nextInt()]++;
while (levels[k] < n)
{
cnt++;
for (int i = k - 1; i >= 0; i--)
{
if (levels[i] > 0)
{
levels[i]--;
levels[i + 1]++;
}
}
}
output.println(cnt);
}
void Run() throws Exception
{
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader buffer = new BufferedReader(new FileReader("test.in"));
PrintStream output = System.out;
Solve(buffer, output);
}
}
} | Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 4021d9d3584e00f3dbec2fecca8ee34e | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayDeque;
public class Main {
private static StreamTokenizer in;
private static PrintWriter out;
private static BufferedReader inB;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
inB = new BufferedReader(new InputStreamReader(System.in));
in = new StreamTokenizer(inB);
out = new PrintWriter(System.out);
}
private static int pow(int a, int n) {
int ans = 1;
for(int i = 0; i<n; i++)ans *= a;
return ans;
}
public static void main(String[] args)throws Exception{
int n = nextInt(), k = nextInt();
int[] mas = new int[n];
for(int i = 0; i<n; i++)mas[i] = nextInt();
int count = 1;
m:for(;;count++) {
int last = k;
for(int i = n-1; i>=0; i--) {
if(mas[i] == last)continue;
last = mas[i];
mas[i]++;
}
if(last == k) {
count--;
break;
}
}
System.out.println(count);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | ac7b874d4fae2890c033766154abf3f2 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class PB {
public static void main(String[] args) {
PB m = new PB();
m.start();
}
private void start() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int solder[] = new int[k+1];
for(int i=0; i<n; i++)
solder[sc.nextInt()]++;
int num = 0;
while(solder[k] != n){
num++;
for(int i=k; 0<i; i--){
if(solder[i-1] != 0){
solder[i-1]--;
solder[i]++;
}
}
}
System.out.println(num);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 6444853520a21538a1e4d029f9939360 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.start();
}
private void start() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int solder[] = new int[k+1];
for(int i=0; i<n; i++)
solder[sc.nextInt()]++;
int num = 0;
while(solder[k] != n){
num++;
for(int i=k; 0<i; i--){
if(solder[i-1] != 0){
solder[i-1]--;
solder[i]++;
}
}
}
System.out.println(num);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 28ff5acb8c8239e918aab50fa7bb5232 | train_000.jsonl | 1298908800 | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank β some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class B {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = 0,k = 0;
String[]use = br.readLine().split(" +");
n = Integer.parseInt(use[0]);
k = Integer.parseInt(use[1]);
int[]ranks = new int[k+1];
Arrays.fill(ranks, 0);
use = br.readLine().split(" +");
for(int i = 0 ; i < use.length ; i++){
int r = Integer.parseInt(use[i]);
ranks[r]++;
}
int res = 0;
while(ranks[k] != n){
boolean[]changed = new boolean[ranks.length];
for(int i = 1 ; i < ranks.length-1 ; i++){
if(ranks[i] == 0)continue;
ranks[i]--;
changed[i+1] = true;
}
for(int i = 1 ; i < ranks.length ; i++){
if(changed[i])ranks[i]++;
}
res++;
}
System.out.println(res);
}
}
| Java | ["4 4\n1 2 2 3", "4 3\n1 1 1 1"] | 2 seconds | ["4", "5"] | NoteIn the first example the ranks will be raised in the following manner:1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins. | Java 6 | standard input | [
"implementation"
] | 3d6411d67c85f6293f1999ccff2cd8ba | The first line contains two integers n and k (1ββ€βn,βkββ€β100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1ββ€βiββ€βn, 1ββ€βaiββ€βk). | 1,200 | Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank. | standard output | |
PASSED | 5d50a0b4580daf698e119b043914bb48 | train_000.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class MainClass
{
static int[] map;
static int[] map1;
static HashSet<Integer> h1;
static HashSet<Integer> h;
public static void main(String args[])throws IOException
{
Reader in = new Reader();
int t = in.nextInt();
StringBuilder stringBuilder = new StringBuilder();
while (t-- > 0)
{
int n = in.nextInt();
int[] A = new int[n];
map = new int[n + 10];
map1 = new int[n + 10];
h = new HashSet<>();
h1 = new HashSet<>();
for (int i=0;i<n;i++)
{
map[A[i] = in.nextInt()]++;
map1[A[i]]++;
h.add(A[i]);
h1.add(A[i]);
}
int l = 0;
int r = n;
int ans = -1;
while (l <= r)
{
map = Arrays.copyOf(map1, n + 10);
h = (HashSet<Integer>) h1.clone();
int mid = (l + r) / 2;
if (rearrangeString(A, mid))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
stringBuilder.append(ans - 1).append("\n");
}
System.out.println(stringBuilder);
}
public static boolean rearrangeString(int[] A, int k)
{
if(k==0)
return true;
//sort the chars by frequency
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer c1, Integer c2){
return map[c2]-map[c1];
}
});
for(int c: h)
queue.add(c);
int len = A.length;
while(!queue.isEmpty()){
int cnt = Math.min(k, len);
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<cnt; i++){
if(queue.isEmpty())
return false;
int c = queue.poll();
map[c]--;
if(map[c]>0){
temp.add(c);
}
len--;
}
for(int c: temp)
queue.add(c);
}
return true;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.