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 | 77d235b914537e3e412469fd2871d3fa | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
public class Temp {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String s = in.nextLine();
Stack<Character> st = new Stack<Character>();
boolean del = true;
while (del){
del = false;
st.clear();
for (int i = 0; i < s.length(); ++i)
if (!st.empty() && s.charAt(i) == st.peek()){
del = true;
st.pop();
}
else
st.push(s.charAt(i));
s = st.toString().replaceAll("(\\,|\\[|\\ |\\])", "");
}
System.out.print(s);
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | eecbe5ba5fe1c3f423859d78b6af76d3 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class P81A {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
String str = scan.next();
Stack<Integer> stack = new Stack<Integer>();
for(int j = 0, i = 0; i < str.length(); i++)
{
j = stack.empty() ? i-1 : stack.peek();
while(j >= 0 && i < str.length() && str.charAt(j) == str.charAt(i))
{
stack.pop();
j = stack.empty() ? i-1 :stack.peek();
i++;
if(stack.empty()) break;
}
if (i < str.length()) stack.push(i);
}
StringBuilder sb = new StringBuilder();
while(!stack.empty()) sb.append(str.charAt(stack.pop()));
System.out.print(sb.reverse());
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 27a34dc6c5ff9496e5c223ea3a1d640c | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 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 P1 implements Runnable {
private void solve() throws IOException {
String s = nextToken();
StringBuilder stack = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (stack.length() > 0 && stack.charAt(stack.length() - 1) == s.charAt(i)) {
stack.deleteCharAt(stack.length() - 1);
} else {
stack.append(s.charAt(i));
}
}
writer.println(stack.toString());
}
public static void main(String[] args) {
new P1().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | e9d483315833337d07f9746d93d50e6b | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.Scanner;
public class A_Plugin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
char[] cs = line.toCharArray();
char[] out = new char[cs.length];
int tos = 0;
for (int i = 0; i < cs.length; i++) {
if(tos == 0 || out[tos - 1] != cs[i]) out[tos++] = cs[i];
else tos--;
}
System.out.println(new String(out, 0, tos));
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | cd9951b0596353c721ab33a59fb4c079 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class Plagin
{
public static void main(String[] s)
{
Scanner in = new Scanner(System.in);
String data = in.next();
char [] result = data.toCharArray();
LinkedList<Character>list = new LinkedList<Character>();
for (int i = 0; i < result.length; i++)
{
list.add(result[i]);
}
ListIterator<Character> iter = list.listIterator();
boolean flag = false;
while(iter.next()!=null&&iter.hasNext())
{
iter.previous();
if(iter.next() == iter.next())
{
iter.remove();
iter.previous();
iter.remove();
}
if(iter.nextIndex() == 0)
{
}
else
{
if(list.size()>0)
{
iter.previous();
}
else
{
break;
}
}
}
if(list.size()!=0)
{
iter = list.listIterator();
for (int i = 0; i < list.size(); i++)
{
System.out.print(iter.next());
}
}
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 413e1445284e7e4a7d732372f1006064 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.AccessControlException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main implements Runnable {
private void solve() throws IOException {
LinkedList<Integer> l = new LinkedList<Integer>();
String s = nextToken();
for (int i = 0; i < s.length(); i++) {
Integer ch = (int) s.charAt(i);
if (l.isEmpty()) {
l.push(ch);
} else {
Integer last = l.peek();
if (ch.equals(last)) {
l.pop();
} else {
l.push(ch);
}
}
}
Iterator<Integer> it = l.descendingIterator();
while (it.hasNext()) {
writer.print(String.format("%c", it.next()));
}
writer.println();
}
private int getNumTest() throws IOException {
return 1;
}
public static void main(String[] args) {
new Main().run();
}
private static boolean LOCAL = false;
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
int numTest = 1;
int test = 1;
public void run() {
try {
LOCAL = (System.getenv("LOCAL") != null);
} catch (AccessControlException e) {
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
if (LOCAL) {
inputStream = new FileInputStream("input");
} else {
inputStream = System.in;
}
outputStream = System.out;
reader = new BufferedReader(new InputStreamReader(inputStream));
writer = new PrintWriter(outputStream);
tokenizer = null;
numTest = getNumTest();
for (test = 1; test <= numTest; test++) {
solve();
}
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 319f43ea12901f393a33245f51d20070 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.*;
public class Plugin {
public static void main(String[] args) throws IOException {
InputStream in = new BufferedInputStream(System.in);
OutputStream out = new BufferedOutputStream(System.out);
int[] buffer = new int[2 * 10 * 10 * 10 * 10 * 10 + 3];
int pos = 0, readed;
buffer[0] = 0;
while((readed = in.read()) != -1) {
if(buffer[pos] != readed) {
buffer[++pos] = readed;
}
else {
pos -= 1;
}
}
for(int i = 1; i <= pos; ++i) {
out.write(buffer[i]);
}
out.close();
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 72f4e54029f8138d1b3e60aaf74d0e4f | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class p81A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
solve(s);
}
static void solve(String s) {
int len = s.length();
if (len == 1) {
System.out.println(s);
return;
}
char[] cArray = s.toCharArray();
Wrapper w = null;
for (int i = len - 1; i >= 0; i--) {
if (w == null) {
w = new Wrapper(cArray[i]);
} else {
if(cArray[i] == w.c){
w = w.next;
}else{
Wrapper temp = w;
w = new Wrapper(cArray[i]);
w.next = temp;
}
}
}
StringBuilder sb = new StringBuilder();
while (w != null) {
sb.append(w.c);
w = w.next;
}
System.out.println(sb);
}
}
class Wrapper {
char c;
Wrapper next;
public Wrapper(char c) {
this.c = c;
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 4d691044705ca623e4de8e4df19bcb18 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class p81AA {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
solve(s);
}
static void solve(String s) {
int len = s.length();
if (len < 3) {
System.out.println(s);
} else {
Stack<Character> stack = new Stack<Character>();
stack.push(s.charAt(len - 1));
for (int i = len - 2; i >= 0; i--) {
char c = s.charAt(i);
if (stack.isEmpty()) {
stack.push(c);
} else {
if (stack.peek() == c) {
stack.pop();
} else {
stack.push(c);
}
}
}
StringBuilder sb = new StringBuilder();
do {
sb.append(stack.pop());
} while (!stack.isEmpty());
System.out.println(sb.toString());
}
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | da0e86629ad01a3a165afea81aa55c90 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner cin=new Scanner(System.in);
while(cin.hasNext())
{
String s=cin.next();
char stack[]=new char[200005];
int stackn=0;
for(int flag=0;flag<s.length();flag++)
{
if(stackn==0)
{
stack[stackn++]=s.charAt(flag);
}
else if(stack[stackn-1]==s.charAt(flag))
{
stackn--;
}
else
{
stack[stackn++]=s.charAt(flag);
}
}
for(int flag=0;flag<stackn;flag++)
{
System.out.print(stack[flag]);
}
System.out.println();
}
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 45684066d2c7deabc74ddb8370d8b593 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
StringBuffer sb = new StringBuffer(in.nextLine());
StringBuilder ans = new StringBuilder();
int x = 0;
for (int i = 0; i < sb.length(); i++) {
if (x == 0) {
ans.append(sb.charAt(i));
++x;
} else if (sb.charAt(i) == ans.charAt(x - 1)) {
ans.deleteCharAt(x - 1);
--x;
} else {
ans.append(sb.charAt(i));
++x;
}
}
System.out.println(ans.toString());
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | a1e2d036d9f95250ac0c840a97939b3d | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
ArrayDeque<Character> st = new ArrayDeque<Character>();
char c;
for (int i=0; i<cur.length(); i++) {
c = cur.charAt(i);
if (st.isEmpty() || c!=st.peek())
st.push(c);
else
st.poll();
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.removeLast());
System.out.println(ans);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | c70a3f57f512a0772afbf0165711a918 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
Deque<Character> st = new ArrayDeque<Character>();
for (int i=0; i<cur.length(); i++) {
char c = cur.charAt(i);
if (st.isEmpty() || c!=st.peek())
st.push(c);
else
st.poll();
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.pollLast());
System.out.println(ans.toString());
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | d94e20b2c0e556c79d0a707bb11c5183 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
ArrayDeque<Character> st = new ArrayDeque<Character>();
char c;
for (int i=0; i<cur.length(); i++) {
c = cur.charAt(i);
if (st.isEmpty() || c!=st.peek())
st.push(c);
else
st.poll();
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.pollLast());
System.out.println(ans);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | a3472cadc17d2e24d396d135c4292b05 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
ArrayDeque<Character> st = new ArrayDeque<Character>();
st.push(cur.charAt(0));
char c;
for (int i=1; i<cur.length(); i++) {
c = cur.charAt(i);
if (st.isEmpty() || c!=st.peek())
st.push(c);
else
st.pop();
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.removeLast());
System.out.println(ans);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | b6520300e4c7c9921a10052f465b3328 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
ArrayDeque<Character> st = new ArrayDeque<Character>();
char c;
for (int i=0; i<cur.length(); i++) {
c = cur.charAt(i);
if (st.isEmpty() || c!=st.peek())
st.push(c);
else
st.pop();
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.removeLast());
System.out.println(ans);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | edc8e2b5f28e7071a265ac83d53d9b1b | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
public class LOL {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String cur = in.nextLine();
Deque<Character> st = new ArrayDeque<Character>();
for (int i=0; i<cur.length(); i++) {
st.push(cur.charAt(i));
while(!st.isEmpty()) {
char c = st.poll();
if (st.isEmpty() || c!=st.peek()) {
st.push(c);
break;
} else
st.poll();
}
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.pollLast());
System.out.println(ans.toString());
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 3e8acbfc1254411d7828868dd7ae76f7 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class LOL {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cur = in.readLine();
Deque<Character> st = new ArrayDeque<Character>();
for (int i=0; i<cur.length(); i++) {
st.push(cur.charAt(i));
while(!st.isEmpty()) {
char c = st.poll();
if (st.isEmpty() || c!=st.peek()) {
st.push(c);
break;
} else
st.poll();
}
}
StringBuilder ans = new StringBuilder();
while(!st.isEmpty())
ans.append(st.pollLast());
System.out.println(ans.toString());
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | dedc54975b6c78ca2f19fa064fcf81c6 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
StringBuilder SB = new StringBuilder();
//LinkedList<String> all = new LinkedList<String>();
Stack<Character> stack = new Stack<Character>();
stack.push(in.charAt(0));
for(int a=1;a<in.length();a++){
char p = in.charAt(a);
if(stack.isEmpty()){stack.add(p);continue;}
char z= stack.peek();
if(z==p){
stack.pop();
}
else{
stack.add(p);
}
}
while(!stack.isEmpty()){
SB.append(stack.pop());
}
System.out.print(SB.reverse());
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 0e010c67bdef0f4e1a2aa7d7e8016030 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.*;
import java.util.*;
public class main {
public static void main(String[] args) throws Exception{
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
String in = sc.readLine();
StringBuilder SB = new StringBuilder();
ArrayDeque<Character> AD = new ArrayDeque<Character>();
AD.push(in.charAt(0));
for(int a=1;a<in.length();a++){
char p = in.charAt(a);
if(AD.isEmpty()){AD.push(p);continue;}
char z= AD.peek();
if(z==p){
AD.pop();
}
else{
AD.push(p);
}
}
while(!AD.isEmpty()){
SB.append(AD.removeLast());
}
System.out.print(SB);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 204f99f27423fad1a0db7480533d3f44 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.*;
import java.util.*;
public class main {
public static void main(String[] args) throws Exception{
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
String in = sc.readLine();
StringBuilder SB = new StringBuilder();
ArrayDeque<Character> AD = new ArrayDeque<Character>();
AD.push(in.charAt(0));
for(int a=1;a<in.length();a++){
// char p = in.charAt(a);
//
// if(AD.isEmpty()){AD.push(p);continue;}
// char z= AD.peek();
// if(z==p){
// AD.pop();
// }
// else{
// AD.push(p);
// }
char c = in.charAt(a);
if (AD.isEmpty() || c!=AD.peek())
AD.push(c);
else
AD.poll();
}
while(!AD.isEmpty()){
SB.append(AD.removeLast());
}
System.out.print(SB);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 05d7bf7533b46d7e89999e4b7b83015e | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | /*
* Hello! You are trying to hack my solution, are you? =)
* Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number.
* And I'm just too lazy to create a new .java for every task.
* And if you were successful to hack my solution, please, send me this test as a message or to [email protected].
* It can help me improve my skills and i'd be very grateful for that.
* Sorry for time you spent reading this message. =)
* Good luck, unknown rival. =)
* */
import java.io.*;
import java.math.*;
import java.util.*;
public class Abra {
// double d = 2.2250738585072012e-308;
void solve() throws IOException {
char[] a = nextString().toCharArray();
char[] s = new char[a.length];
int ns = 0;
for(int i=0;i<a.length;++i) {
s[ns++] = a[i];
while(ns >= 2 && s[ns-1] == s[ns-2]) ns -= 2;
}
out.println(new String(s, 0, ns));
}
public static void main(String[] args) throws IOException {
new Abra().run();
}
StreamTokenizer in;
PrintWriter out;
boolean oj;
BufferedReader br;
void init() throws IOException {
oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
br = new BufferedReader(reader);
in = new StreamTokenizer(br);
out = new PrintWriter(writer);
}
long beginTime;
void run() throws IOException {
beginTime = System.currentTimeMillis();
long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
init();
solve();
long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endTime = System.currentTimeMillis();
if (!oj) {
System.out.println("Memory used = " + (endMem - beginMem));
System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
System.out.println("Running time = " + (endTime - beginTime));
}
out.flush();
}
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
myLib lib = new myLib();
void time() {
System.out.print("It's ");
System.out.println(System.currentTimeMillis() - beginTime);
}
static class myLib {
long fact(long x) {
long a = 1;
for (long i = 2; i <= x; i++) {
a *= i;
}
return a;
}
long digitSum(String x) {
long a = 0;
for (int i = 0; i < x.length(); i++) {
a += x.charAt(i) - '0';
}
return a;
}
long digitSum(long x) {
long a = 0;
while (x > 0) {
a += x % 10;
x /= 10;
}
return a;
}
long digitMul(long x) {
long a = 1;
while (x > 0) {
a *= x % 10;
x /= 10;
}
return a;
}
int digitCubesSum(int x) {
int a = 0;
while (x > 0) {
a += (x % 10) * (x % 10) * (x % 10);
x /= 10;
}
return a;
}
double pif(double ax, double ay, double bx, double by) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
double pif3D(double ax, double ay, double az, double bx, double by, double bz) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz));
}
double pif3D(double[] a, double[] b) {
return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]));
}
long gcd(long a, long b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
long c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
long c = b;
b = a;
a = c;
}
}
return b;
}
int gcd(int a, int b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
int c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
int c = b;
b = a;
a = c;
}
}
return b;
}
long lcm(long a, long b) {
return a * b / gcd(a, b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int countOccurences(String x, String y) {
int a = 0, i = 0;
while (true) {
i = y.indexOf(x);
if (i == -1) break;
a++;
y = y.substring(i + 1);
}
return a;
}
int[] findPrimes(int x) {
boolean[] forErato = new boolean[x - 1];
List<Integer> t = new Vector<Integer>();
int l = 0, j = 0;
for (int i = 2; i < x; i++) {
if (forErato[i - 2]) continue;
t.add(i);
l++;
j = i * 2;
while (j < x) {
forErato[j - 2] = true;
j += i;
}
}
int[] primes = new int[l];
Iterator<Integer> iterator = t.iterator();
for (int i = 0; iterator.hasNext(); i++) {
primes[i] = iterator.next().intValue();
}
return primes;
}
int rev(int x) {
int a = 0;
while (x > 0) {
a = a * 10 + x % 10;
x /= 10;
}
return a;
}
class myDate {
int d, m, y;
int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public myDate(int da, int ma, int ya) {
d = da;
m = ma;
y = ya;
if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) {
d = 1;
m = 1;
y = 9999999;
}
}
void incYear(int x) {
for (int i = 0; i < x; i++) {
y++;
if (m == 2 && d == 29) {
m = 3;
d = 1;
return;
}
if (m == 3 && d == 1) {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
m = 2;
d = 29;
}
return;
}
}
}
boolean less(myDate x) {
if (y < x.y) return true;
if (y > x.y) return false;
if (m < x.m) return true;
if (m > x.m) return false;
if (d < x.d) return true;
if (d > x.d) return false;
return true;
}
void inc() {
if ((d == 31) && (m == 12)) {
y++;
d = 1;
m = 1;
} else {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
ml[1] = 29;
}
if (d == ml[m - 1]) {
m++;
d = 1;
} else
d++;
}
}
}
int partition(int n, int l, int m) {// n - sum, l - length, m - every
// part
// <= m
if (n < l) return 0;
if (n < l + 2) return 1;
if (l == 1) return 1;
int c = 0;
for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) {
c += partition(n - i, l - 1, i);
}
return c;
}
int rifmQuality(String a, String b) {
if (a.length() > b.length()) {
String c = a;
a = b;
b = c;
}
int c = 0, d = b.length() - a.length();
for (int i = a.length() - 1; i >= 0; i--) {
if (a.charAt(i) == b.charAt(i + d)) c++;
else
break;
}
return c;
}
String numSym = "0123456789ABCDEF";
String ZFromXToYNotation(int x, int y, String z) {
if (z.equals("0")) return "0";
String a = "";
// long q = 0, t = 1;
BigInteger q = BigInteger.ZERO, t = BigInteger.ONE;
for (int i = z.length() - 1; i >= 0; i--) {
q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48)));
t = t.multiply(BigInteger.valueOf(x));
}
while (q.compareTo(BigInteger.ZERO) == 1) {
a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a;
q = q.divide(BigInteger.valueOf(y));
}
return a;
}
double angleFromXY(int x, int y) {
if ((x == 0) && (y > 0)) return Math.PI / 2;
if ((x == 0) && (y < 0)) return -Math.PI / 2;
if ((y == 0) && (x > 0)) return 0;
if ((y == 0) && (x < 0)) return Math.PI;
if (x > 0) return Math.atan((double) y / x);
else {
if (y > 0) return Math.atan((double) y / x) + Math.PI;
else
return Math.atan((double) y / x) - Math.PI;
}
}
static boolean isNumber(String x) {
try {
Integer.parseInt(x);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
static boolean stringContainsOf(String x, String c) {
for (int i = 0; i < x.length(); i++) {
if (c.indexOf(x.charAt(i)) == -1) return false;
}
return true;
}
long pow(long a, long n) { // b > 0
if (n == 0) return 1;
long k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
int pow(int a, int n) { // b > 0
if (n == 0) return 1;
int k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double pow(double a, int n) { // b > 0
if (n == 0) return 1;
double k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double log2(double x) {
return Math.log(x) / Math.log(2);
}
int lpd(int[] primes, int x) {// least prime divisor
int i;
for (i = 0; primes[i] <= x / 2; i++) {
if (x % primes[i] == 0) {
return primes[i];
}
}
;
return x;
}
int np(int[] primes, int x) {// number of prime number
for (int i = 0; true; i++) {
if (primes[i] == x) return i;
}
}
int[] dijkstra(int[][] map, int n, int s) {
int[] p = new int[n];
boolean[] b = new boolean[n];
Arrays.fill(p, Integer.MAX_VALUE);
p[s] = 0;
b[s] = true;
for (int i = 0; i < n; i++) {
if (i != s) p[i] = map[s][i];
}
while (true) {
int m = Integer.MAX_VALUE, mi = -1;
for (int i = 0; i < n; i++) {
if (!b[i] && (p[i] < m)) {
mi = i;
m = p[i];
}
}
if (mi == -1) break;
b[mi] = true;
for (int i = 0; i < n; i++)
if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i];
}
return p;
}
boolean isLatinChar(char x) {
if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true;
else
return false;
}
boolean isBigLatinChar(char x) {
if (x >= 'A' && x <= 'Z') return true;
else
return false;
}
boolean isSmallLatinChar(char x) {
if (x >= 'a' && x <= 'z') return true;
else
return false;
}
boolean isDigitChar(char x) {
if (x >= '0' && x <= '9') return true;
else
return false;
}
class NotANumberException extends Exception {
private static final long serialVersionUID = 1L;
String mistake;
NotANumberException() {
mistake = "Unknown.";
}
NotANumberException(String message) {
mistake = message;
}
}
class Real {
String num = "0";
long exp = 0;
boolean pos = true;
long length() {
return num.length();
}
void check(String x) throws NotANumberException {
if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character.");
long j = 0;
for (long i = 0; i < x.length(); i++) {
if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) {
if (j == 0) j = 1;
else
if (j == 5) j = 6;
else
throw new NotANumberException("Unexpected sign.");
} else
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) j = 2;
else
if (j == 1) j = 2;
else
if (j == 2)
;
else
if (j == 3) j = 4;
else
if (j == 4)
;
else
if (j == 5) j = 6;
else
if (j == 6)
;
else
throw new NotANumberException("Unexpected digit.");
} else
if (x.charAt((int) i) == '.') {
if (j == 0) j = 3;
else
if (j == 1) j = 3;
else
if (j == 2) j = 3;
else
throw new NotANumberException("Unexpected dot.");
} else
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
if (j == 2) j = 5;
else
if (j == 4) j = 5;
else
throw new NotANumberException("Unexpected exponent.");
} else
throw new NotANumberException("O_o.");
}
if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end.");
}
public Real(String x) throws NotANumberException {
check(x);
if (x.charAt(0) == '-') pos = false;
long j = 0;
String e = "";
boolean epos = true;
for (long i = 0; i < x.length(); i++) {
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) num += x.charAt((int) i);
if (j == 1) {
num += x.charAt((int) i);
exp--;
}
if (j == 2) e += x.charAt((int) i);
}
if (x.charAt((int) i) == '.') {
if (j == 0) j = 1;
}
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
j = 2;
if (x.charAt((int) (i + 1)) == '-') epos = false;
}
}
while ((num.length() > 1) && (num.charAt(0) == '0'))
num = num.substring(1);
while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) {
num = num.substring(0, num.length() - 1);
exp++;
}
if (num.equals("0")) {
exp = 0;
pos = true;
return;
}
while ((e.length() > 1) && (e.charAt(0) == '0'))
e = e.substring(1);
try {
if (e != "") if (epos) exp += Long.parseLong(e);
else
exp -= Long.parseLong(e);
} catch (NumberFormatException exc) {
if (!epos) {
num = "0";
exp = 0;
pos = true;
} else {
throw new NotANumberException("Too long exponent");
}
}
}
public Real() {
}
String toString(long mantissa) {
String a = "", b = "";
if (exp >= 0) {
a = num;
if (!pos) a = '-' + a;
for (long i = 0; i < exp; i++)
a += '0';
for (long i = 0; i < mantissa; i++)
b += '0';
if (mantissa == 0) return a;
else
return a + "." + b;
} else {
if (exp + length() <= 0) {
a = "0";
if (mantissa == 0) {
return a;
}
if (mantissa < -(exp + length() - 1)) {
for (long i = 0; i < mantissa; i++)
b += '0';
return a + "." + b;
} else {
if (!pos) a = '-' + a;
for (long i = 0; i < mantissa; i++)
if (i < -(exp + length())) b += '0';
else
if (i + exp >= 0) b += '0';
else
b += num.charAt((int) (i + exp + length()));
return a + "." + b;
}
} else {
if (!pos) a = "-";
for (long i = 0; i < exp + length(); i++)
a += num.charAt((int) i);
if (mantissa == 0) return a;
for (long i = exp + length(); i < exp + length() + mantissa; i++)
if (i < length()) b += num.charAt((int) i);
else
b += '0';
return a + "." + b;
}
}
}
}
boolean containsRepeats(int... num) {
Set<Integer> s = new TreeSet<Integer>();
for (int d : num)
if (!s.contains(d)) s.add(d);
else
return true;
return false;
}
int[] rotateDice(int[] a, int n) {
int[] c = new int[6];
if (n == 0) {
c[0] = a[1];
c[1] = a[5];
c[2] = a[2];
c[3] = a[0];
c[4] = a[4];
c[5] = a[3];
}
if (n == 1) {
c[0] = a[2];
c[1] = a[1];
c[2] = a[5];
c[3] = a[3];
c[4] = a[0];
c[5] = a[4];
}
if (n == 2) {
c[0] = a[3];
c[1] = a[0];
c[2] = a[2];
c[3] = a[5];
c[4] = a[4];
c[5] = a[1];
}
if (n == 3) {
c[0] = a[4];
c[1] = a[1];
c[2] = a[0];
c[3] = a[3];
c[4] = a[5];
c[5] = a[2];
}
if (n == 4) {
c[0] = a[0];
c[1] = a[2];
c[2] = a[3];
c[3] = a[4];
c[4] = a[1];
c[5] = a[5];
}
if (n == 5) {
c[0] = a[0];
c[1] = a[4];
c[2] = a[1];
c[3] = a[2];
c[4] = a[3];
c[5] = a[5];
}
return c;
}
int min(int... a) {
int c = Integer.MAX_VALUE;
for (int d : a)
if (d < c) c = d;
return c;
}
int max(int... a) {
int c = Integer.MIN_VALUE;
for (int d : a)
if (d > c) c = d;
return c;
}
int pos(int x) {
if (x > 0) return x;
else
return 0;
}
long pos(long x) {
if (x > 0) return x;
else
return 0;
}
double maxD(double... a) {
double c = Double.MIN_VALUE;
for (double d : a)
if (d > c) c = d;
return c;
}
double minD(double... a) {
double c = Double.MAX_VALUE;
for (double d : a)
if (d < c) c = d;
return c;
}
int[] normalizeDice(int[] a) {
int[] c = a.clone();
if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0);
else
if (c[2] == 0) c = rotateDice(c, 1);
else
if (c[3] == 0) c = rotateDice(c, 2);
else
if (c[4] == 0) c = rotateDice(c, 3);
else
if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0);
while (c[1] != min(c[1], c[2], c[3], c[4]))
c = rotateDice(c, 4);
return c;
}
boolean sameDice(int[] a, int[] b) {
for (int i = 0; i < 6; i++)
if (a[i] != b[i]) return false;
return true;
}
final double goldenRatio = (1 + Math.sqrt(5)) / 2;
final double aGoldenRatio = (1 - Math.sqrt(5)) / 2;
long Fib(int n) {
if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
else
return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5));
}
class japaneeseComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int ai = 0, bi = 0;
boolean m = false, ns = false;
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true;
else
return -1;
}
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true;
else
return 1;
}
a += "!";
b += "!";
int na = 0, nb = 0;
while (true) {
if (a.charAt(ai) == '!') {
if (b.charAt(bi) == '!') break;
return -1;
}
if (b.charAt(bi) == '!') {
return 1;
}
if (m) {
int ab = -1, bb = -1;
while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (ab == -1) ab = ai;
ai++;
}
while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (bb == -1) bb = bi;
bi++;
}
m = !m;
if (ab == -1) {
if (bb == -1) continue;
else
return 1;
}
if (bb == -1) return -1;
while (a.charAt(ab) == '0' && ab + 1 != ai) {
ab++;
if (!ns) na++;
}
while (b.charAt(bb) == '0' && bb + 1 != bi) {
bb++;
if (!ns) nb++;
}
if (na != nb) ns = true;
if (ai - ab < bi - bb) return -1;
if (ai - ab > bi - bb) return 1;
for (int i = 0; i < ai - ab; i++) {
if (a.charAt(ab + i) < b.charAt(bb + i)) return -1;
if (a.charAt(ab + i) > b.charAt(bb + i)) return 1;
}
} else {
m = !m;
while (true) {
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') {
if (a.charAt(ai) < b.charAt(bi)) return -1;
if (a.charAt(ai) > b.charAt(bi)) return 1;
ai++;
bi++;
} else
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1;
else
if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1;
else
break;
}
}
}
if (na < nb) return 1;
if (na > nb) return -1;
return 0;
}
}
Random random = new Random();
}
void readIntArray(int[] a) throws IOException {
for (int i = 0; i < a.length; i++)
a[i] = nextInt();
}
String readChars(int l) throws IOException {
String r = "";
for (int i = 0; i < l; i++)
r += (char) br.read();
return r;
}
class myFraction {
long num = 0, den = 1;
void reduce() {
long d = lib.gcd(num, den);
num /= d;
den /= d;
}
myFraction(long ch, long zn) {
num = ch;
den = zn;
reduce();
}
myFraction add(myFraction t) {
long nd = lib.lcm(den, t.den);
myFraction r = new myFraction(nd / den * num + nd / t.den * t.num, nd);
r.reduce();
return r;
}
public String toString() {
return num + "/" + den;
}
int lev(String s1, String s2) {
int[][] distance = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); i++)
distance[i][0] = i;
for (int j = 0; j <= s2.length(); j++)
distance[0][j] = j;
for (int i = 1; i <= s1.length(); i++)
for (int j = 1; j <= s2.length(); j++)
distance[i][j] = Math.min(Math.min(distance[i - 1][j] + 1, distance[i][j - 1] + 1), distance[i - 1][j - 1] + ((s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : 1));
return distance[s1.length()][s2.length()];
}
}
class myPoint {
myPoint(int a, int b) {
x = a;
y = b;
}
int x, y;
boolean equals(myPoint a) {
if (x == a.x && y == a.y) return true;
else
return false;
}
public String toString() {
return x + ":" + y;
}
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 988a57f64acc6ec8ba01c91117309797 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] s) {
Scanner sc = new Scanner(System.in);
Stack<Character> S = new Stack<Character>();
String Text = sc.next();
S.push(Text.charAt(0));
for (int i = 1; i < Text.length(); i++) {
if (S.empty()) {
S.push(Text.charAt(i));
} else {
if (S.peek() == Text.charAt(i)) {
S.pop();
} else {
S.push(Text.charAt(i));
}
}
}
for (int j = 0; j < S.size(); j++) {
System.out.print(S.elementAt(j));
}
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 32047dd77688da0e4cb049582d7c9db8 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.Scanner;
public class A81 {
public static void main(String ...args) {
Scanner sc = new Scanner(System.in);
char[] in = sc.next().trim().toCharArray();
StringBuffer res = new StringBuffer();
res.append(in[0]);
for (int i=1; i<in.length; i++)
{
if (res.length()!=0 && res.charAt(res.length()-1)==in[i])
res.deleteCharAt(res.length()-1);
else
res.append(in[i]);
}
System.out.println(res);
}
} | Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 501bba5922679fca77c881eddb7a41ca | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.*;
import java.util.*;
public class plugin{
public static void main(String args[]) throws IOException{
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
String a = lector.readLine();
Stack<Character> s = new Stack<Character>();
s.push(a.charAt(0));
for(int n = 1;n<a.length();n++){
/*boolean entro = false;
if(n<a.length()-1 && a.charAt(n)==a.charAt(n+1)){
a = a.substring(0,n)+a.substring(n+2,a.length());
entro = true;
//System.out.println(a);
}
if(n>0 && entro)
n-=2;
else if(entro)n--;*/
//malditas estructuras
//boolean entro = false;
char tmp = 'a';
if(!s.isEmpty() && (tmp=s.peek())!=a.charAt(n)){
//s.push(tmp);
s.push(a.charAt(n));
//entro = true;
}else if(s.isEmpty())
s.push(a.charAt(n));
else if(tmp==a.charAt(n))
s.pop();
//System.out.println(s+" "+entro);
}
StringBuilder res = new StringBuilder("");
while(!s.isEmpty())
res = res.append(s.pop());//res = s.pop()+res;
System.out.println(res.reverse());
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | adf40a6e06a7dffe1635e922449951f0 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | /**
* Problem:
* Source: ', Round
* Link:
*
* @author Alexei Ostrovski
*/
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class DoublesSolver {
public static void main(String[] args) {
//redirect input and output
/*try {
System.setIn(new FileInputStream("input.txt"));
//System.setOut(new PrintStream("output.txt"));
} catch (IOException e) {
//nothing
}*/
Scanner sc = new Scanner(System.in);
//for (int i = 0; i < 99999; i++)
// System.out.print("ab");
//for (int i = 0; i < 50000; i++)
// System.out.print("ba");
//read data
String line = sc.next();
//solve
String result = line;
int[] next = new int[line.length() + 1];
int[] prev = new int[line.length() + 1];
for (int i = 0; i <= line.length(); i++)
{
next[i] = i;
prev[i] = i - 1;
}
int cur = 0;
while (next[cur + 1] < result.length())
{
while ((cur < 0) || ((next[cur + 1] < result.length()) &&
(result.charAt(cur) != result.charAt(next[cur + 1]))))
{
cur = next[cur + 1];
}
//System.out.println(prev[cur] + " " + cur);
if (next[cur + 1] < result.length()) //we have something to delete
{
next[prev[cur] + 1] = next[next[cur + 1] + 1];
prev[next[next[cur + 1] + 1]] = prev[cur];
cur = prev[cur];
}
}
//output
cur = -1;
while (next[cur + 1] < line.length())
{
cur = next[cur + 1];
System.out.print(line.charAt(cur));
}
System.out.println();
//System.out.println(result);
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 51aa00a0ed6d31ad34660bdd7241e9df | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.util.*;
public class PlugIn {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
StringBuilder s = new StringBuilder(input.next());
StringBuilder out = new StringBuilder(s.charAt(0) + "");
for(int i = 1; i<s.length(); i++)
{
//System.out.println(out);
if(out.length()==0)
{
out.append(s.charAt(i));
continue;
}
if(s.charAt(i) == out.charAt(out.length()-1))
out.deleteCharAt(out.length()-1);
else
out.append(s.charAt(i));
}
System.out.println(out);
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 008afcadd843c0cf37938776522d2507 | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
Stack<Character> S = new Stack<Character>();
S.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
if(!S.isEmpty() && S.peek() == s.charAt(i))
S.pop();
else
S.push(s.charAt(i));
}
for (char c : S) {
System.out.print(c);
}
System.out.println();
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | d56c6673278a70ccf05e3319080a3a3e | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Solution {
public StringBuilder plug(StringBuilder input){
int len = input.length();
int prev_len = 0;
//if(len == 0)
//return "";
while(prev_len - len != 0){
StringBuilder s = new StringBuilder();
int i = 0;
while(i < len){
if(i+1 < len && input.charAt(i) == input.charAt(i+1) ){
i = i + 2;
}
else if (i < len){
s.append(input.charAt(i));
++i;
}
}
input = s;
prev_len = len;
len = input.length();
}
return input;
}
public StringBuilder plug1(StringBuilder input){
int len = input.length();
int prev_len = 0;
//if(len == 0)
//return "";
Stack<Character> sta = new Stack<>();
for(int i = 0; i < len; ++i){
if(sta.empty()){
sta.push(input.charAt(i));
}
else if(sta.peek() == input.charAt(i) )
sta.pop();
else{
sta.push(input.charAt(i));
}
}
StringBuilder result = new StringBuilder();
while(!sta.empty()){
result.append(sta.pop());
}
return result.reverse();
}
public static void main(String[] args) throws IOException{
//"abcddcba"
//
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Solution a = new Solution();
String s = reader.readLine();
StringBuilder input = new StringBuilder(s);
StringBuilder result = a.plug1(input);
System.out.println(result.toString());
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | f4feb9564fedfd905da2e699b08ea59a | train_000.jsonl | 1304485200 | Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class ProblemA {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
String newLine = clean2(line);
System.out.println(newLine);
// while (true) {
// String newLine = clean2(line);
// if (newLine.length() == line.length()) {
// System.out.println(newLine);
// break;
// }
// line = newLine;
// }
}
private static String clean2(String line) {
char[] s = new char[line.length()];
int l = 0;
for(int i=0; i < line.length(); i++) {
char c = line.charAt(i);
if (l > 0 && s[l-1] == c)
l --;
else
s[l++] = c;
}
return new String(s, 0, l);
}
private static String clean(String line) {
StringBuffer t = new StringBuffer();
char pc = 0;
int state = 0;
for (char c : line.toCharArray()) {
if (state == 0) {
pc = c;
state = 1;
} else {
if (pc != c) {
if (t.length() > 0 && t.charAt(t.length()-1) == pc) {
t.deleteCharAt(t.length()-1);
}
else
t.append(pc);
pc = c;
} else {
state = 0;
}
}
}
if (state == 1)
t.append(pc);
return t.toString();
}
}
| Java | ["hhoowaaaareyyoouu", "reallazy", "abacabaabacabaa"] | 1 second | ["wre", "rezy", "a"] | null | Java 6 | standard input | [
"implementation"
] | 26f1b8c3cb83603c904e1508df4067f4 | The input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. | 1,400 | Print the given string after it is processed. It is guaranteed that the result will contain at least one character. | standard output | |
PASSED | 0be05bbc47fc14768a007c495712c77a | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
public class C {
static int n, nums[];
static boolean valid(int pos) {
if (pos > n)
return true;
if (pos % 2 == 0) {
if (pos < n && nums[pos] <= nums[pos + 1])
return false;
if (pos > 1 && nums[pos - 1] >= nums[pos])
return false;
} else {
if (pos < n && nums[pos] >= nums[pos + 1])
return false;
if (pos > 1 && nums[pos - 1] <= nums[pos])
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(bf.readLine());
String l[] = bf.readLine().split(" ");
nums = new int[n + 1];
for (int i = 0; i < n; i++) {
nums[i + 1] = Integer.parseInt(l[i]);
}
int x = 0;
int pos[] = new int[4];
for (int i = 1; i < nums.length - 1; i++) {
if (i % 2 == 0) {
if (nums[i] <= nums[i + 1]) {
if (x >= 4) {
System.out.println(0);
return;
}
pos[x++] = i;
}
} else {
if (nums[i] >= nums[i + 1]) {
if (x >= 4) {
System.out.println(0);
return;
}
pos[x++] = i;
}
}
}
int ans = 0;
if (x == 1) {
for (int i = 1; i < nums.length; i++) {
swap(pos[0], i);
if (valid(i) && valid(pos[0]))
ans++;
swap(pos[0], i);
}
pos[0]++;
for (int i = 1; i < nums.length; i++) {
if (i == pos[0] - 1)
continue;
swap(pos[0], i);
if (valid(i) && valid(pos[0]))
ans++;
swap(pos[0], i);
}
} else if (x == 2) {
HashSet<String> res = new HashSet<String>();
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < 2; j++) {
swap(pos[j], i);
pos[2] = i;
if (valid(pos, 3)) {
add(i, pos[j], res);
}
swap(pos[j], i);
swap(pos[j] + 1, i);
pos[2] = i;
if (valid(pos, 3)) {
add(i, pos[j] + 1, res);
}
swap(pos[j] + 1, i);
}
}
ans = res.size();
} else {
HashSet<String> res = new HashSet<String>();
for (int i = 0; i < pos.length; i++) {
for (int k = 0; k < x; k++) {
swap(pos[i], pos[k]);
if (valid(pos, x)) {
add(pos[i], pos[k], res);
}
swap(pos[i], pos[k]);
swap(pos[i] + 1, pos[k]);
if (valid(pos, x)) {
add(pos[i] + 1, pos[k], res);
}
swap(pos[i] + 1, pos[k]);
swap(pos[i] + 1, pos[k] + 1);
if (valid(pos, x)) {
add(pos[i] + 1, pos[k] + 1, res);
}
swap(pos[i] + 1, pos[k] + 1);
swap(pos[i], pos[k] + 1);
if (valid(pos, x)) {
add(pos[i], pos[k] + 1, res);
}
swap(pos[i], pos[k] + 1);
}
}
ans = res.size();
}
System.out.println(ans);
}
private static void add(int i, int j, HashSet<String> res) {
if (i > j) {
int tmp = i;
i = j;
j = tmp;
}
res.add(i + " " + j);
}
private static boolean valid(int[] pos, int x) {
for (int i = 0; i < x; i++) {
if (!valid(pos[i]) || !valid(pos[i] + 1))
return false;
}
return true;
}
private static void swap(int i, int i2) {
int tmp = nums[i];
nums[i] = nums[i2];
nums[i2] = tmp;
}
} | Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | ca7a5467d4c4e8cfd92f93a74853c511 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.*;
import java.util.*;
public class Copy_4_of_CF {
FastScanner in;
PrintWriter out;
class O implements Comparable<O> {
int x, y;
public O(int x, int y) {
super();
this.x = Math.min(x, y);
this.y = Math.max(x, y);
}
@Override
public int compareTo(O o) {
if (x != o.x) {
return Integer.compare(x, o.x);
}
return Integer.compare(y, o.y);
}
}
void solve() {
int n = in.nextInt();
int[] a = new int[n];
ArrayList<Integer> pos = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i + 1 < n; i++) {
if (i % 2 == 0) {
if (a[i + 1] <= a[i]) {
pos.add(i);
}
} else {
if (a[i + 1] >= a[i]) {
pos.add(i);
}
}
}
if (pos.size() > 20) {
out.println(0);
return;
}
ArrayList<Integer> inter = new ArrayList<>();
HashSet<Integer> was = new HashSet<>();
for (int x : pos) {
if (!was.contains(x)) {
inter.add(x);
was.add(x);
}
if (!was.contains(x + 1)) {
inter.add(x + 1);
was.add(x + 1);
}
}
int result = 0;
ArrayList<Integer> inter2 = inter;
if (inter.size() <= 3) {
inter2 = new ArrayList<>();
for (int x = 0; x < n; x++) {
inter2.add(x);
}
}
ArrayList<O> o = new ArrayList<>();
for (int f : inter) {
for (int s : inter2) {
int tmp = a[f];
a[f] = a[s];
a[s] = tmp;
{
boolean ok = true;
for (int x : pos) {
if (x % 2 == 0) {
if (a[x + 1] <= a[x]) {
ok = false;
break;
}
} else {
if (a[x + 1] >= a[x]) {
ok = false;
break;
}
}
}
for (int x : new int[] { f - 1, f, s - 1, s }) {
if (x >= 0 && x + 1 < n) {
if (x % 2 == 0) {
if (a[x + 1] <= a[x]) {
ok = false;
break;
}
} else {
if (a[x + 1] >= a[x]) {
ok = false;
break;
}
}
}
}
if (ok) {
o.add(new O(f, s));
}
}
tmp = a[f];
a[f] = a[s];
a[s] = tmp;
}
}
Collections.sort(o);
for (int i = 0; i < o.size(); i++) {
if (i == 0
|| (o.get(i).x != o.get(i - 1).x || o.get(i).y != o
.get(i - 1).y)) {
result++;
}
}
out.println(result);
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test2.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 Copy_4_of_CF().runIO();
}
} | Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | efaf16645c8e9c5ac7d2e8b413345686 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | /*
* Code Author: Akshay Miterani
* DA-IICT
*/
import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
static double eps=(double)1e-6;
static long mod=(int)1e9+7;
public static void main(String args[]){
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
//----------My Code----------
int n=in.nextInt();
int a[]=new int[n+2];
if(n%2==0){
a[n+1]=Integer.MIN_VALUE;
}
else{
a[n+1]=Integer.MAX_VALUE;
}
a[0]=Integer.MAX_VALUE;
for(int i=1;i<=n;i++){
a[i]=in.nextInt();
}
boolean v[]=new boolean[n+2];
ArrayList<Integer> index=new ArrayList<Integer>();
for(int i=1;i<=n;i++){
if(i%2==0){
if(a[i]>Math.max(a[i-1], a[i+1]))
v[i]=true;
else
index.add(i);
}
else{
if(a[i]<Math.min(a[i-1], a[i+1]))
v[i]=true;
else{
index.add(i);
}
}
}
if(index.size()>6){
System.out.println("0");
return;
}
HashSet<Integer> first=new HashSet<Integer>();
for(int x:index){
first.add(x);
}
int ans=0;
HashSet<String> h=new HashSet<String>();
for(int x:index){
for(int i=1;i<=n;i++){
if(x==i)
continue;
HashSet<Integer> second=new HashSet<Integer>();
int tmp=a[x];
a[x]=a[i];
a[i]=tmp;
boolean ok=true;
for(int j=i-1;j<=i+1;j++){
if(j==0 || j==n+1)
continue;
if(j%2==0){
if(a[j]>Math.max(a[j-1], a[j+1])){
if(!v[j])
second.add(j);
}
else{
ok=false;
}
}
else{
if(a[j]<Math.min(a[j-1], a[j+1])){
if(!v[j])
second.add(j);
}
else{
ok=false;
}
}
}
for(int j=x-1;j<=x+1;j++){
if(j==0 || j==n+1)
continue;
if(j%2==0){
if(a[j]>Math.max(a[j-1], a[j+1])){
if(!v[j])
second.add(j);
}
else{
ok=false;
}
}
else{
if(a[j]<Math.min(a[j-1], a[j+1])){
if(!v[j])
second.add(j);
}
else{
ok=false;
}
}
}
tmp=a[x];
a[x]=a[i];
a[i]=tmp;
if(first.equals(second) && ok){
//System.out.println(x+" "+i);
h.add(Integer.toString(Math.max(x, i))+"|"+Integer.toString(Math.min(x, i)));
ans++;
}
}
}
System.out.println(h.size());
//---------------The End------------------
}
static int recursiveBinarySearch(int[][] sortedArray, int start, int end, int key) {
if (start <= end) {
int mid = start + (end - start) / 2;
if (key < sortedArray[mid][0]) {
return recursiveBinarySearch(sortedArray, start, mid, key);
} else if (key > sortedArray[mid][0]) {
return recursiveBinarySearch(sortedArray, mid+1, end , key);
} else {
return mid;
}
}
return -(start + 1);
}
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
static long gcd(long x, long y)
{
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
static class Pair implements Comparable<Pair>{
long x;
long y;
int i;
Pair(long xx,long yy){
x=xx;
y=yy;
}
@Override
public int compareTo(Pair o) {
if(this.y>=o.y)
return 1;
else
return 0;
}
}
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 nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | c309768105dfbcf6adf36596eb5aff83 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 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.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class BearAndUpDown {
private static class Pair implements Comparable<Pair> {
int i, j;
Pair(int a, int b) {
i = Math.min(a, b);
j = Math.max(a, b);
}
@Override
public String toString() {
return i + " " + j;
}
@Override
public int compareTo(Pair p) {
if (i != p.i)
return i - p.i;
if (j != p.j)
return j - p.j;
return 0;
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean isNice(int[] a, int i, int j) {
int n = a.length - 1;
for (int k = i; k < j; k++) {
if (k < 1 || k > n)
continue;
if ((k & 1) != 0) {
if (k + 1 <= n && a[k] >= a[k + 1])
return false;
} else if (k + 1 <= n && a[k] <= a[k + 1])
return false;
}
return true;
}
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
int n = sc.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = sc.nextInt();
TreeSet<Integer> bad = new TreeSet<>();
for (int i = 1; i < n; i++) {
if ((i & 1) == 0 && a[i] <= a[i + 1]) {
bad.add(i);
bad.add(i + 1);
} else if ((i & 1) != 0 && a[i] >= a[i + 1]) {
bad.add(i);
bad.add(i + 1);
}
}
int x = bad.size();
if (x > 6) {
System.out.println(0);
} else {
TreeSet<Pair> set = new TreeSet<>();
for (int i : bad) {
int idx = i;
for (int j = 1; j <= n; j++) {
if (idx == j)
continue;
swap(a, idx, j);
boolean f = isNice(a, j - 1, j + 1);
for (int k : bad)
f &= isNice(a, k - 1, k + 1);
if (f)
set.add(new Pair(idx, j));
swap(a, idx, j);
}
}
System.out.println(set.size());
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(InputStream is) throws IOException {
br = new BufferedReader(new InputStreamReader(is));
}
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());
}
}
}
| Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | be9530d8c5d8b67b1f67ea45b2a42cb1 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
import static java.lang.StrictMath.*;
import static java.util.stream.Collectors.*;
public class TaskC {
private static final String INPUT_FILE = "input.txt";
private static final String ONLINE_JUDGE = "ONLINE_JUDGE";
public static void main(String[] args) {
boolean oj = System.getProperty(ONLINE_JUDGE) != null;
try {
InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE));
PrintWriter writer = new PrintWriter(System.out);
new Solver(reader).run(writer);
writer.close();
}
catch (IOException e) {
new RuntimeException(e);
}
}
}
class Solver {
public Solver(InputReader reader) throws IOException {
n = reader.nextInt();
a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = reader.nextInt();
}
}
public void run(PrintWriter writer) {
v = new boolean[n];
int cnt = 0;
p = new TreeSet<>();
for (int i = 0; i < n-1; ++i) {
if ((i%2 == 0) ? (a[i] >= a[i+1]) : (a[i] <= a[i+1])) {
++cnt;
p.add(i);
p.add(i+1);
}
}
if (cnt > 4) {
writer.println(0);
return;
}
else {
pairs = new HashSet<Long>();
for (int position: p) {
for (int i = 0; i < n; ++i) {
if (i != position) {
change(position, i);
}
}
}
writer.println(pairs.size());
}
}
private void change(int i, int j) {
swap(i, j);
boolean ok = valid(i-1) && valid(i) && valid(i+1) && valid(j-1) && valid(j) && valid(j+1);
if (ok)
for (int x: p) {
if (!valid(x-1) || !valid(x) || !valid(x+1)) {
ok = false;
break;
}
}
swap(i, j);
if (ok) {
if (i < j) {
int t = i;
i = j;
j = t;
}
pairs.add((long)i*n + j);
}
}
private boolean valid(int position) {
if (position < 0 || position >= n-1) {
return true;
}
else {
return position%2 == 0 ? a[position] < a[position+1] : a[position] > a[position+1];
}
}
private void swap(int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
private Set<Integer> p;
private Set<Long> pairs;
private int n;
private int[] a;
private boolean[] v;
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 1<<15);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double parseDouble() {
return Double.parseDouble(next());
}
}
| Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 7a38f3752220e4175eaad044ad386629 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.util.*;
import java.io.*;
public class TaskC {
private FastScanner in;
private PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
int[] t = new int[n];
List<Integer> bad = new ArrayList<>();
Set<Integer> badSet = new TreeSet<>();
for (int i = 0; i < n; i++) {
t[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
if (!checkIndex(i, t)) {
bad.add(i);
badSet.add(i);
}
}
if (bad.size() > 6) {
out.println(0);
return;
}
int res = 0;
for (int i = 0; i < bad.size(); i++) {
for (int j = 0; j < n; j++) {
int s1 = bad.get(i), s2 = j;
if (badSet.contains(s2) && s1 >= s2) {
continue;
}
int tmp = t[s1];
t[s1] = t[s2];
t[s2] = tmp;
List<Integer> toCheck = new ArrayList<>();
toCheck.addAll(bad);
toCheck.add(j);
boolean ok = true;
for (int k : toCheck) {
if (!checkIndex(k, t) || !checkIndex(k - 1, t) || !checkIndex(k + 1, t)) {
ok = false;
break;
}
}
if (ok) res++;
tmp = t[s1];
t[s1] = t[s2];
t[s2] = tmp;
}
}
out.println(res);
}
boolean checkIndex(int i, int[] t) {
if (i < 0 || i >= t.length) {
return true;
}
if (i % 2 == 1) {
return (i == 0 || t[i - 1] < t[i]) && (i == t.length - 1 || t[i + 1] < t[i]);
} else {
return (i == 0 || t[i - 1] > t[i]) && (i == t.length - 1 || t[i + 1] > t[i]);
}
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] arg) {
new TaskC().run();
}
} | Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 89eb63aebae31647744ab5d40f764e28 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class BearandUpDown {
static HashSet<Integer> set;
static int n;
static int vals[];
static boolean check(){
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Integer i = (Integer) iterator.next();
if(i == n - 1)
continue;
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
return false;
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
return false;
}
if(set.contains(vals.length - 1) && n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
vals = new int[n];
set = new HashSet<>();
for (int i = 0; i < n; i++) {
vals[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
set.add(i);
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
set.add(i);
}
if(n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
set.add(n - 1);
if(set.size() > 6)
{
System.out.println(0);
return;
}
int ans = 0;
HashSet<Integer> set3 = new HashSet<>();
for(Integer x : set){
set3.add(x);
}
for (Iterator iterator = set3.iterator(); iterator.hasNext();) {
Integer x = (Integer) iterator.next();
for (int i = 0; i < n; i++) {
if(i > x || !set3.contains(i)) {
int tmp = vals[x];
vals[x] = vals[i];
vals[i] = tmp;
boolean b = set.contains(i);
set.add(i);
if(check()) ans++;
if(!b) set.remove(i);
vals[i] = vals[x];
vals[x] = tmp;
}
}
}
System.out.println(ans);
}
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\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 917929b3efd287d8d0ba4a0f00e5ecc8 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class BearandUpDown {
static HashSet<Integer> set2;
static int n;
static int vals[];
static boolean check(){
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Integer i = (Integer) iterator.next();
if(i == n - 1)
continue;
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
return false;
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
return false;
}
if(set2.contains(vals.length - 1) && n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
vals = new int[n];
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
vals[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
set.add(i);
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
set.add(i);
}
if(n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
set.add(n - 1);
if(set.size() > 6)
{
System.out.println(0);
return;
}
set2 = new HashSet<>();
for(Integer x : set){
set2.add(x);
if(x > 0 ) set2.add(x - 1);
if(x < n - 1 ) set2.add(x + 1);
}
int ans = 0;
HashSet<Integer> set3 = new HashSet<>();
for(Integer x : set2){
set3.add(x);
}
for (Iterator iterator = set3.iterator(); iterator.hasNext();) {
Integer x = (Integer) iterator.next();
for (int i = 0; i < n; i++) {
if(i > x || !set3.contains(i)) {
int tmp = vals[x];
vals[x] = vals[i];
vals[i] = tmp;
boolean b = set2.contains(i);
set2.add(i);
if(check()) ans++;
if(!b) set2.remove(i);
vals[i] = vals[x];
vals[x] = tmp;
}
}
}
System.out.println(ans);
}
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\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 9e81a11eed9465decaaa682a4920472b | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class BearandUpDown {
static HashSet<Integer> set2;
static int n;
static int vals[];
static boolean check(){
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Integer i = (Integer) iterator.next();
if(i == n - 1)
continue;
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
return false;
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
return false;
}
if(set2.contains(vals.length - 1) && n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
vals = new int[n];
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
vals[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
if(i % 2 == 0 && (vals[i] >= vals[i + 1] || i > 0 && vals[i] >= vals[i - 1]))
set.add(i);
if(i % 2 == 1 && (vals[i] <= vals[i + 1] || i > 0 && vals[i] <= vals[i - 1]))
set.add(i);
}
if(n > 1 && (n % 2 == 1 && vals[n - 1] >= vals[n - 2] || n % 2 == 0 && vals[n - 1] <= vals[n - 2]))
set.add(n - 1);
if(set.size() > 6)
{
System.out.println(0);
return;
}
set2 = new HashSet<>();
for(Integer x : set){
set2.add(x);
if(x > 0 ) set2.add(x - 1);
if(x < n - 1 ) set2.add(x + 1);
}
int ans = 0;
HashSet<Integer> set3 = new HashSet<>();
for(Integer x : set2){
set3.add(x);
}
for (Iterator iterator = set3.iterator(); iterator.hasNext();) {
Integer x = (Integer) iterator.next();
for (int i = 0; i < n; i++) {
if(i > x || !set3.contains(i)) {
int tmp = vals[x];
vals[x] = vals[i];
vals[i] = tmp;
boolean b = set2.contains(i);
set2.add(i);
if(check()) ans++;
if(!b) set2.remove(i);
vals[i] = vals[x];
vals[x] = tmp;
}
}
}
if(n == 149997 && n == 0)
System.out.println(set.size());
// for(Integer x : set3){
// for (int i = 0; i < n; i++) {
// if(i > x || !set3.contains(i)) {
// int tmp = vals[x];
// vals[x] = vals[i];
// vals[i] = tmp;
// boolean b = set2.contains(i);
// set2.add(i);
// if(check()) ans++;
// if(!b) set.remove(i);
// vals[i] = vals[x];
// vals[x] = tmp;
// }
// }
//
// }
System.out.println(ans);
}
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\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 30142a01012c75069aa6b35558bcef48 | train_000.jsonl | 1458376500 | The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class TaskC {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
TaskC taskC = new TaskC();
taskC.open();
taskC.solve();
taskC.close();
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String str = in.readLine();
if (str == null) return null;
else st = new StringTokenizer(str);
}
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());
}
private void close() {
out.close();
}
private long checkSimple(int n) {
int ret = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int tmp;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
if (check(0, n) == 0) ret++;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
return ret;
}
int[] a;
private void solve() throws IOException {
int n = nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
out.println(slv(n));
}
public long slv(int n) throws IOException {
int fails = check(0, n, true);
switch (fails) {
case 0: {
throw new IOException();
}
case 1: {
int bad1 = failed.get(0);
int bad2 = bad1 + 1;
int ans = 0;
if (trySwp(bad1, bad2, false)) ans++;
for (int i = 0; i < n; i++) {
if (i == bad1 || i == bad2) continue;
if (trySwp(i, bad1, false)) ans++;
if (trySwp(i, bad2, false)) ans++;
}
return ans;
}
case 2: {
int bad1 = failed.get(0);
int bad2 = bad1 + 1;
int bad3 = failed.get(1);
int bad4 = bad3 + 1;
int ans = 0;
if (bad2 == bad3) {
if (trySwp(bad1, bad2, false)) ans++;
if (trySwp(bad1, bad4, false)) ans++;
if (trySwp(bad3, bad4, false)) ans++;
for (int i = 0; i < n; i++) {
if (i == bad1 || i == bad2 || i == bad4) continue;
if (trySwp(i, bad2, false)) ans++;
}
} else {
if (trySwp(bad1, bad3, false)) ans++;
if (trySwp(bad1, bad4, false)) ans++;
if (trySwp(bad2, bad3, false)) ans++;
if (trySwp(bad2, bad4, false)) ans++;
}
return ans;
}
case 3: {
Set<Integer> bads = new HashSet<>();
for (Integer cur : failed) {
bads.add(cur);
bads.add(cur + 1);
}
ArrayList<Integer> bs = new ArrayList<Integer>(bads);
int ans = 0;
for (int i = 0; i < bs.size(); i++) {
for (int j = i + 1; j < bs.size(); j++) {
if (trySwp(bs.get(i), bs.get(j), true)) ans++;
}
}
return ans;
}
case 4: {
if (trySwp(failed.get(1), failed.get(3), false)) return 1;
return 0;
}
default:
return 0;
}
}
boolean trySwp(int i, int j, boolean fullCheck) {
if (Math.max(i, j) >= a.length) return false;
boolean result = true;
int tmp;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
if (fullCheck) {
if (check(0, a.length) != 0) result = false;
}
if (check(i - 10, i + 10) != 0) result = false;
if (check(j - 10, j + 10) != 0) result = false;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
return result;
}
ArrayList<Integer> failed;
private int check(int start, int end) {
return check(start, end, false);
}
private int check(int start, int end, boolean calcF) {
int fails = 0;
if (calcF) {
failed = new ArrayList<Integer>();
}
int s = Math.max(start, 0);
int e = Math.min(end, a.length);
for (int i = s; i < e - 1; i++) {
if ((i % 2 == 0) && (a[i] >= a[i + 1])
|| (i % 2 != 0) && (a[i] <= a[i + 1])) {
fails++;
if (calcF) {
failed.add(i);
}
}
}
return fails;
}
private void open() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
} | Java | ["5\n2 8 4 7 7", "4\n200 150 100 50", "10\n3 2 1 4 1 4 1 4 1 4", "9\n1 2 3 4 5 6 7 8 9"] | 2 seconds | ["2", "1", "8", "0"] | NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2β=β8 with t4β=β7. Swap t1β=β2 with t5β=β7. In the second sample, there is only one wayΒ β Limak should swap t1β=β200 with t4β=β50. | Java 8 | standard input | [
"implementation",
"brute force"
] | e5b0e43beaca9baf428afec6ce454c50 | The first line of the input contains one integer n (2ββ€βnββ€β150β000)Β β the length of the sequence. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β150β000) β the initial sequence. It's guaranteed that the given sequence is not nice. | 1,900 | Print the number of ways to swap two elements exactly once in order to get a nice sequence. | standard output | |
PASSED | 4c4451eb58d0ffd568a23a2175eae3c5 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class C {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new BufferedInputStream(System.in, 1 << 20));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 1 << 20);
int n = in.nextInt();
int m = in.nextInt();
int[][] map = new int[n][];
int[][] rows = new int[n][];
int[][] cols = new int[m][];
for (int i = 0; i < m; i++) {
cols[i] = new int[n];
}
for (int i = 0; i < n; i++) {
map[i] = new int[m];
rows[i] = new int[m];
for (int j = 0; j < m; j++) {
int x = in.nextInt();
map[i][j] = x;
rows[i][j] = x;
cols[j][i] = x;
}
}
for (int i = 0; i < n; i++) {
rows[i] = IntStream.of(rows[i]).sorted().distinct().toArray();
}
for (int i = 0; i < m; i++) {
cols[i] = IntStream.of(cols[i]).sorted().distinct().toArray();
}
int[][] result = new int[n][];
for (int i = 0; i < n; i++) {
result[i] = new int[m];
for (int j = 0; j < m; j++) {
int x = map[i][j];
int a = lt(rows[i], x);
int b = lt(cols[j], x);
result[i][j] = Math.max(a, b) + Math.max(rows[i].length - a, cols[j].length - b);
}
}
for (int i = 0; i < n; i++) {
out.write(IntStream.of(result[i]).boxed().map(Objects::toString).collect(Collectors.joining(" ")));
out.write("\n");
}
out.flush();
}
private static int lt(int[] xs, int n) {
if (xs.length == 0) return 0;
if (xs[0] >= n) return 0;
if (xs[xs.length - 1] < n) return xs.length;
return lt(xs, 0, xs.length - 1, n);
}
private static int lt(int[] xs, int l, int r, int n) {
if (r - l <= 1) return l + 1;
int m = (l + r ) / 2;
return (xs[m] < n) ? lt(xs, m, r, n) : lt(xs, l, m, n);
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 94e71471456bac5b9af9b819a8d896e1 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class C {
public static void main(String[] args) {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt(), m = scan.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
grid[i][j] = scan.nextInt();
int[][] rgrid = new int[n][m];
int[][] cgrid = new int[n][m];
int[] r = new int[n];
int[] c = new int[m];
for(int i = 0; i < n; i++) {
TreeSet<Integer> s = new TreeSet<Integer>();
for(int j = 0; j < m; j++) s.add(grid[i][j]);
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
int idx = 1;
for(int j : s) if(!map.containsKey(j)) map.put(j, idx++);
int max = 0;
for(int j = 0; j < m; j++) {
rgrid[i][j] = map.get(grid[i][j]);
max = Math.max(rgrid[i][j], max);
}
r[i] = max;
}
for(int i = 0; i < m; i++) {
TreeSet<Integer> s = new TreeSet<Integer>();
for(int j = 0; j < n; j++) s.add(grid[j][i]);
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
int idx = 1;
for(int j : s) if(!map.containsKey(j)) map.put(j, idx++);
int max = 0;
for(int j = 0; j < n; j++) {
cgrid[j][i] = map.get(grid[j][i]);
max = Math.max(cgrid[j][i], max);
}
c[i] = max;
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int d = Math.abs(cgrid[i][j]-rgrid[i][j]);
if(cgrid[i][j] < rgrid[i][j]) out.print(Math.max(c[j]+d, r[i]));
else if(cgrid[i][j] > rgrid[i][j]) out.print(Math.max(c[j], r[i]+d));
else out.print(Math.max(c[j], r[i]));
out.print(" ");
}
out.println();
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
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 double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 2f39145a9366a0fcf58d6deac315b157 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.math.*;
import java.util.*;
//import javafx.util.*;
import java.io.*;
public class Prg10 {
PrintWriter pw = new PrintWriter(System.out);
Random rnd = new Random();
int a;
void run() {
a = ni();
int b = ni();
int[][] m = new int[a][b], pstr = new int[a][b], pstl = new int[a][b];
TreeSet<Integer>[] str = new TreeSet[a], stl = new TreeSet[b];
for(int q=0; q<a; q++) str[q] = new TreeSet<>();
for(int w=0; w<b; w++) stl[w] = new TreeSet<>();
for(int q=0; q<a; q++){
for(int w=0; w<b; w++){
m[q][w] = ni();
str[q].add(m[q][w]);
}
HashMap<Integer, Integer> h = new HashMap<>();
int u =1;
for(int i : str[q]) h.put(i, u++);
for(int w=0; w<b; w++) pstr[q][w] = h.get(m[q][w]);
}
for(int w=0; w<b; w++){
for(int q=0; q<a; q++) stl[w].add(m[q][w]);
HashMap<Integer, Integer> h = new HashMap<>();
int u =1;
for(int i : stl[w]) h.put(i, u++);
for(int q=0; q<a; q++) pstl[q][w] = h.get(m[q][w]);
}
for(int q=0; q<a; q++){
for(int w=0; w<b; w++){
int p1 = pstr[q][w], p2 = pstl[q][w];
pw.print((Math.max(p1,p2)+Math.max(str[q].size()-p1, stl[w].size()-p2))+" ");
}
pw.println();
}
pw.flush();
}
static class PyraSort {
private static int heapSize;
public static void sort(int[] a) {
buildHeap(a);
while (heapSize > 1) {
swap(a, 0, heapSize - 1);
heapSize--;
heapify(a, 0);
}
}
private static void buildHeap(int[] a) {
heapSize = a.length;
for (int i = a.length / 2; i >= 0; i--) {
heapify(a, i);
}
}
private static void heapify(int[] a, int i) {
int l = 2 * i + 2;
int r = 2 * i + 1;
int largest = i;
if (l < heapSize && a[i] < a[l]) {
largest = l;
}
if (r < heapSize && a[largest] < a[r]) {
largest = r;
}
if (i != largest) {
swap(a, i, largest);
heapify(a, largest);
}
}
private static void swap(int[] a, int i, int j) {
a[i] ^= a[j] ^= a[i];
a[j] ^= a[i];
}
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Prg10().run();
}
}, "1", 1 << 28).start();
}
InputStream is = System.in;
private byte[] inbuf = new byte[1<<16];
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))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private String nline(){
int b = readByte();
StringBuilder sb = new StringBuilder();
while (b!=10) {
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();
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 54a3b43a9d016fd9c23f1645f7eea951 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package Round545;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
*
* @author Hemant Dhanuka
*/
public class C {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int a[][]=new int[n][m];
int h[][]=new int[n][m];
int v[][]=new int[n][m];
int hlen[]=new int[n];
int vlen[]=new int[m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[i][j]=s.nextInt();
}
}
//deciding order of horizontal numbers
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<n;i++){
map.clear();
int temp[]=new int[m];
temp=Arrays.copyOf(a[i],m);
Arrays.sort(temp);
int pos=0;
int last=-1;
for(int j=0;j<m;j++){
if(temp[j]!=last){
pos++;
map.put(temp[j],pos);
last=temp[j];
}
}
hlen[i]=pos;
for(int j=0;j<m;j++){
h[i][j]=map.get(a[i][j]);
}
}
//decide order of vertical numbers
//copy data in v
for(int j=0;j<m;j++){
int temp[]=new int[n];
for(int i=0;i<n;i++){
temp[i]=a[i][j];
}
Arrays.sort(temp);
map.clear();
int pos=0;
int last=-1;
for(int i=0;i<n;i++){
if(temp[i]!=last){
pos++;
map.put(temp[i],pos);
last=temp[i];
}
}
vlen[j]=pos;
for(int i=0;i<n;i++){
v[i][j]=map.get(a[i][j]);
}
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int ans=0;
if(h[i][j]>v[i][j]){
ans=Math.max(hlen[i], h[i][j]-v[i][j]+vlen[j]);
}else{
ans=Math.max(vlen[j], v[i][j]-h[i][j]+hlen[i]);
}
sb.append(ans).append(" ");
}
sb.append("\n");
}
System.out.println(sb);
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 272807239061a25a89565921bbd67d2e | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void solution(BufferedReader reader, PrintWriter writer)
throws IOException {
In in = new In(reader);
Out out = new Out(writer);
int n = in.nextInt();
int m = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++)
grid[i] = in.nextIntArray(m);
int[][] h = new int[n][m];
int[] maxh = new int[n];
for (int i = 0; i < n; i++) {
int[][] data = new int[m][2];
for (int j = 0; j < m; j++)
data[j] = new int[] { grid[i][j], j };
Arrays.sort(data, Comparator.comparing((int[] arr) -> arr[0]));
int max = 1;
for (int j = 0; j < m; j++) {
if (j > 0 && data[j][0] > data[j - 1][0])
max++;
h[i][data[j][1]] = max;
}
maxh[i] = max;
}
int[][] v = new int[n][m];
int[] maxv = new int[m];
for (int j = 0; j < m; j++) {
int[][] data = new int[n][2];
for (int i = 0; i < n; i++)
data[i] = new int[] { grid[i][j], i };
Arrays.sort(data, Comparator.comparing((int[] arr) -> arr[0]));
int max = 1;
for (int i = 0; i < n; i++) {
if (i > 0 && data[i][0] > data[i - 1][0])
max++;
v[data[i][1]][j] = max;
}
maxv[j] = max;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int max = Math.max(h[i][j], v[i][j]);
int maxr = Math.max(maxh[i] - h[i][j], maxv[j] - v[i][j]);
out.printb(max + maxr);
}
out.println(' ');
}
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(System.out)));
solution(reader, writer);
writer.close();
}
protected static class In {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public In(BufferedReader reader) {
this.reader = reader;
}
public String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray1(int n) throws IOException {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArraySorted(int n) throws IOException {
int[] a = nextIntArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArray1(int n) throws IOException {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArraySorted(int n) throws IOException {
long[] a = nextLongArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
}
protected static class Out {
private PrintWriter writer;
private static boolean local = System
.getProperty("ONLINE_JUDGE") == null;
public Out(PrintWriter writer) {
this.writer = writer;
}
public void print(char c) {
writer.print(c);
}
public void print(int a) {
writer.print(a);
}
public void printb(int a) {
writer.print(a);
writer.print(' ');
}
public void println(Object a) {
writer.println(a);
}
public void println(Object[] os) {
for (int i = 0; i < os.length; i++) {
writer.print(os[i]);
writer.print(' ');
}
writer.println();
}
public void println(int[] a) {
for (int i = 0; i < a.length; i++) {
writer.print(a[i]);
writer.print(' ');
}
writer.println();
}
public void println(long[] a) {
for (int i = 0; i < a.length; i++) {
writer.print(a[i]);
writer.print(' ');
}
writer.println();
}
public void flush() {
writer.flush();
}
public static void db(Object... objects) {
if (local)
System.out.println(Arrays.deepToString(objects));
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | c23e54a4c7f4b862a4ba6dbedfc9ef70 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class informatics {
public static void main(String[] args) throws IOException{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(scan.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int a[][] = new int[n][m];
int str_bol[][] = new int[n][m];
int str_men[][] = new int[n][m];
int stl_bol[][] = new int[n][m];
int stl_men[][] = new int[n][m];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(scan.readLine());
for (int j = 0; j < m; j++) {
a[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < n; i++) {
ArrayList<Integer> str = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int j = 0; j < m; j++) {
if (!set.contains(a[i][j])) {
str.add(a[i][j]);
set.add(a[i][j]);
}
}
Collections.sort(str);
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int j = 0; j < str.size(); j++) {
map.put(str.get(j), j);
}
for (int j = 0; j < m; j++) {
str_bol[i][j] = str.size() - map.get(a[i][j]) - 1;
str_men[i][j] = map.get(a[i][j]);
}
}
for (int j = 0; j < m; j++) {
ArrayList<Integer> stl = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
if (!set.contains(a[i][j])) {
stl.add(a[i][j]);
set.add(a[i][j]);
}
}
Collections.sort(stl);
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < stl.size(); i++) {
map.put(stl.get(i), i);
}
for (int i = 0; i < n; i++) {
stl_bol[i][j] = stl.size() - map.get(a[i][j]) - 1;
stl_men[i][j] = map.get(a[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.write(1 + Math.max(str_bol[i][j], stl_bol[i][j]) + Math.max(stl_men[i][j], str_men[i][j]) + " ");
}
out.write("\n");
}
out.close();
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | b562a3f66dcd69f2a7bc532ed619d4c9 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] vals = new int[N][M];
ArrayList<Integer>[] rows = new ArrayList[N];
ArrayList<Integer>[] cols = new ArrayList[M];
for(int i = 0; i < N; i++) rows[i] = new ArrayList<>();
for(int i = 0; i < M; i++) cols[i] = new ArrayList<>();
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
vals[i][j] = scanner.nextInt();
rows[i].add(vals[i][j]);
cols[j].add(vals[i][j]);
}
}
//want to know for each elt how many in the row are greater and how many are less
for(int i = 0; i < N; i++) Collections.sort(rows[i]);
for(int i = 0; i < N; i++) {
ArrayList<Integer> list = new ArrayList<>();
list.add(rows[i].get(0));
for(int j = 1; j < M; j++) if ((int)rows[i].get(j) != (int)rows[i].get(j-1)) list.add(rows[i].get(j));
rows[i] = list;
}
for(int j = 0; j < M; j++) Collections.sort(cols[j]);
for(int j = 0; j < M; j++) {
ArrayList<Integer> list = new ArrayList<>();
list.add(cols[j].get(0));
for(int i = 1; i < N; i++) if ((int)cols[j].get(i) != (int)cols[j].get(i-1)) list.add(cols[j].get(i));
cols[j] = list;
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
if (j > 0) out.print(" ");
int rowInd = binSearch(rows[i], vals[i][j]);
int colInd = binSearch(cols[j], vals[i][j]);
int ans = Math.max(rowInd, colInd) + 1 + Math.max(rows[i].size()-rowInd - 1, cols[j].size() - colInd -1);
out.print(ans);
}
out.println();
}
out.flush();
}
public static int binSearch(ArrayList<Integer> list, int t) {
int lo = 0;
int hi = list.size()-1;
while(lo < hi) {
int mid =(lo + hi)/2;
if (list.get(mid) == t) return mid;
if (list.get(mid)< t) lo = mid + 1;
else hi = mid;
}
return lo;
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 4171afe3f37a983d132f2206781a69b2 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
public class Q3 {
public static void main(String[] args) {
InputReader s = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = 1;
// t = s.nextInt();
nexttest:
while (t-- > 0) {
int n = s.nextInt();
int m = s.nextInt();
int[][] a = new int[n][m];
int[][] b = new int[m][n];
int[][] ca = new int[n][m];
int[][] cb = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ca[i][j] = a[i][j] = s.nextInt();
cb[j][i] = b[j][i] = a[i][j];
}
}
for (int i = 0; i < n; i++) {
Arrays.sort(ca[i]);
}
for (int i = 0; i < m; i++) {
Arrays.sort(cb[i]);
}
HashMap<Integer, Integer> mapA[] = new HashMap[n];
HashMap<Integer, Integer> mapB[] = new HashMap[m];
int[] maxA = new int[n];
int[] maxB = new int[m];
for (int i = 0; i < n; i++) {
int curr = 1;
mapA[i] = new HashMap<>();
for (int j = 0; j < m; j++) {
if (!mapA[i].containsKey(ca[i][j])) {
mapA[i].put(ca[i][j], curr++);
}
}
maxA[i] = curr - 1;
}
for (int i = 0; i < m; i++) {
int curr = 1;
mapB[i] = new HashMap<>();
for (int j = 0; j < n; j++) {
if (!mapB[i].containsKey(cb[i][j])) {
mapB[i].put(cb[i][j], curr++);
}
}
maxB[i] = curr - 1;
}
// System.out.println(Arrays.deepToString(ca));
// System.out.println(Arrays.deepToString(cb));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int meRow = mapA[i].get(a[i][j]);
int meCol = mapB[j].get(a[i][j]);
int maxRow = maxA[i];
int maxCol = maxB[j];
if (meRow <= meCol) {
maxRow = maxRow + meCol - meRow;
out.print(Math.max(maxRow, maxCol) + " ");
} else {
maxCol = maxCol + meRow - meCol;
out.print(Math.max(maxRow, maxCol) + " ");
}
}
out.println();
}
}
out.close();
}
public static void printArray(int[] a, PrintWriter out) {
for (int i = 0; i < a.length; i++) {
out.print(a[i]);
out.print(' ');
}
out.println();
}
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;
}
static long gcd(long n1, long n2) {
long r;
while (n2 != 0) {
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | f427d7891b74f4db0ca890aa42a9b680 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
@SuppressWarnings("unchecked")
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = in.readIntMatrix(n, m);
Set<Integer>[] rowSet = new Set[n];
Set<Integer>[] colSet = new Set[m];
IntList[] row = new IntList[n];
IntList[] col = new IntList[m];
for (int i = 0; i < n; i++)
row[i] = new IntList(m);
for (int i = 0; i < m; i++)
col[i] = new IntList(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
row[i].add(a[i][j]);
col[j].add(a[i][j]);
}
}
for (int i = 0; i < n; i++) {
row[i].sortAndUnify();
}
for (int i = 0; i < m; i++) {
col[i].sortAndUnify();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j > 0) out.space();
int rowIndex = row[i].upperBound(a[i][j]);
int colIndex = col[j].upperBound(a[i][j]);
int value = Math.max(rowIndex, colIndex);
value += Math.max(row[i].size() - rowIndex, col[j].size() - colIndex);
out.print(value);
}
out.println();
}
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public int[][] readIntMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
matrix[i] = readIntArray(m);
}
return matrix;
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void space() {
print(' ');
}
public void close() {
super.close();
}
}
static class IntList implements Iterable<Integer> {
public static final int INITIAL_CAPACITY = 4;
private int size;
private int[] array;
public IntList() {
this(INITIAL_CAPACITY);
}
public IntList(int initialCapacity) {
this.array = new int[initialCapacity];
this.size = 0;
}
public IntList(int[] array) {
this.array = Arrays.copyOf(array, array.length);
this.size = this.array.length;
}
public IntList(Collection<Integer> collection) {
this.size = collection.size();
this.array = new int[size];
int index = 0;
for (int e : collection) {
array[index++] = e;
}
}
public void add(int value) {
if (size == array.length) {
ensureCapacity();
}
this.array[this.size++] = value;
}
public int upperBound(int value) {
return upperBound(value, 0, size - 1);
}
private int upperBound(int value, int low, int high) {
if (low < 0 || high >= size)
throw new IllegalArgumentException("Invalid boundaries for lowerBound algorithm");
while (low <= high) {
int mid = low + high >> 1;
if (array[mid] <= value)
low = mid + 1;
else
high = mid - 1;
}
return high;
}
public void sortAndUnify() {
if (size <= 1) return;
Arrays.sort(array, 0, size);
int uniqueSize = 1;
for (int i = 1; i < size; i++) {
if (array[i] != array[i - 1])
uniqueSize++;
}
int[] temp = new int[uniqueSize];
temp[0] = array[0];
for (int i = 1, j = 1; i < size; i++) {
if (array[i] != array[i - 1])
temp[j++] = array[i];
}
array = temp;
size = uniqueSize;
}
public int size() {
return this.size;
}
private void ensureCapacity() {
if (size < array.length)
return;
this.array = Arrays.copyOf(array, array.length << 1);
}
public IntList clone() {
IntList cloned = new IntList(Math.max(1, this.size));
for (int i = 0; i < size; ++i)
cloned.add(array[i]);
return cloned;
}
public Iterator<Integer> iterator() {
return new IntListIterator();
}
private class IntListIterator implements Iterator<Integer> {
private int current;
public IntListIterator() {
this.current = 0;
}
public boolean hasNext() {
return this.current < size;
}
public Integer next() {
return array[current++];
}
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | ff3faa5f9ecdf59b9e63e262ff39eac0 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = in.readIntMatrix(n, m);
IntList[] row = new IntList[n];
IntList[] col = new IntList[m];
for (int i = 0; i < n; i++)
row[i] = new IntList(m);
for (int i = 0; i < m; i++)
col[i] = new IntList(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
row[i].add(a[i][j]);
col[j].add(a[i][j]);
}
}
for (int i = 0; i < n; i++) {
row[i].sortAndUnify();
}
for (int i = 0; i < m; i++) {
col[i].sortAndUnify();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j > 0) out.space();
int rowIndex = row[i].upperBound(a[i][j]);
int colIndex = col[j].upperBound(a[i][j]);
int value = Math.max(rowIndex, colIndex);
value += Math.max(row[i].size() - rowIndex, col[j].size() - colIndex);
out.print(value);
}
out.println();
}
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public int[][] readIntMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
matrix[i] = readIntArray(m);
}
return matrix;
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void space() {
print(' ');
}
public void close() {
super.close();
}
}
static class IntList implements Iterable<Integer> {
public static final int INITIAL_CAPACITY = 4;
private int size;
private int[] array;
public IntList() {
this(INITIAL_CAPACITY);
}
public IntList(int initialCapacity) {
this.array = new int[initialCapacity];
this.size = 0;
}
public IntList(int[] array) {
this.array = Arrays.copyOf(array, array.length);
this.size = this.array.length;
}
public IntList(Collection<Integer> collection) {
this.size = collection.size();
this.array = new int[size];
int index = 0;
for (int e : collection) {
array[index++] = e;
}
}
public void add(int value) {
if (size == array.length) {
ensureCapacity();
}
this.array[this.size++] = value;
}
public int upperBound(int value) {
return upperBound(value, 0, size - 1);
}
private int upperBound(int value, int low, int high) {
if (low < 0 || high >= size)
throw new IllegalArgumentException("Invalid boundaries for lowerBound algorithm");
while (low <= high) {
int mid = low + high >> 1;
if (array[mid] <= value)
low = mid + 1;
else
high = mid - 1;
}
return high;
}
public void sortAndUnify() {
if (size <= 1) return;
Arrays.sort(array, 0, size);
int uniqueSize = 1;
for (int i = 1; i < size; i++) {
if (array[i] != array[i - 1])
uniqueSize++;
}
int[] temp = new int[uniqueSize];
temp[0] = array[0];
for (int i = 1, j = 1; i < size; i++) {
if (array[i] != array[i - 1])
temp[j++] = array[i];
}
array = temp;
size = uniqueSize;
}
public int size() {
return this.size;
}
private void ensureCapacity() {
if (size < array.length)
return;
this.array = Arrays.copyOf(array, array.length << 1);
}
public IntList clone() {
IntList cloned = new IntList(Math.max(1, this.size));
for (int i = 0; i < size; ++i)
cloned.add(array[i]);
return cloned;
}
public Iterator<Integer> iterator() {
return new IntListIterator();
}
private class IntListIterator implements Iterator<Integer> {
private int current;
public IntListIterator() {
this.current = 0;
}
public boolean hasNext() {
return this.current < size;
}
public Integer next() {
return array[current++];
}
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 140c23aa6b0d0018b2bd77ad9c1f25f9 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Asgar Javadov
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = in.readIntMatrix(n, m);
Set<Integer>[] rowSet = new Set[n];
Set<Integer>[] colSet = new Set[m];
for (int i = 0; i < n; i++)
rowSet[i] = new HashSet<>();
for (int i = 0; i < m; i++) {
colSet[i] = new HashSet<>();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
rowSet[i].add(a[i][j]);
colSet[j].add(a[i][j]);
}
}
IntList[] row = new IntList[n];
IntList[] col = new IntList[m];
for (int i = 0; i < n; i++) {
row[i] = new IntList(rowSet[i]);
row[i].sort();
}
for (int i = 0; i < m; i++) {
col[i] = new IntList(colSet[i]);
col[i].sort();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j > 0) out.space();
int rowIndex = row[i].upperBound(a[i][j]);
int colIndex = col[j].upperBound(a[i][j]);
int value = Math.max(rowIndex, colIndex);
value += Math.max(row[i].size() - rowIndex, col[j].size() - colIndex);
out.print(value);
}
out.println();
}
}
}
static class IntList implements Iterable<Integer> {
public static final int INITIAL_CAPACITY = 4;
private int size;
private int[] array;
public IntList() {
this(INITIAL_CAPACITY);
}
public IntList(int initialCapacity) {
this.array = new int[initialCapacity];
this.size = 0;
}
public IntList(int[] array) {
this.array = Arrays.copyOf(array, array.length);
this.size = this.array.length;
}
public IntList(Collection<Integer> collection) {
this.size = collection.size();
this.array = new int[size];
int index = 0;
for (int e : collection) {
array[index++] = e;
}
}
public void add(int value) {
if (size == array.length) {
ensureCapacity();
}
this.array[this.size++] = value;
}
public int upperBound(int value) {
return upperBound(value, 0, size - 1);
}
private int upperBound(int value, int low, int high) {
if (low < 0 || high >= size)
throw new IllegalArgumentException("Invalid boundaries for lowerBound algorithm");
while (low <= high) {
int mid = low + high >> 1;
if (array[mid] <= value)
low = mid + 1;
else
high = mid - 1;
}
return high;
}
public void sort() {
Arrays.sort(array, 0, size);
}
public int size() {
return this.size;
}
private void ensureCapacity() {
if (size < array.length)
return;
this.array = Arrays.copyOf(array, array.length << 1);
}
public IntList clone() {
IntList cloned = new IntList(Math.max(1, this.size));
for (int i = 0; i < size; ++i)
cloned.add(array[i]);
return cloned;
}
public Iterator<Integer> iterator() {
return new IntListIterator();
}
private class IntListIterator implements Iterator<Integer> {
private int current;
public IntListIterator() {
this.current = 0;
}
public boolean hasNext() {
return this.current < size;
}
public Integer next() {
return array[current++];
}
}
}
static class InputReader extends BufferedReader {
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
super(new InputStreamReader(inputStream), 32768);
}
public InputReader(String filename) {
super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.valueOf(next());
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public int[][] readIntMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
matrix[i] = readIntArray(m);
}
return matrix;
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
public OutputWriter(String filename) throws FileNotFoundException {
super(filename);
}
public void space() {
print(' ');
}
public void close() {
super.close();
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 2c82f0de1a1b38a01cdfd1d8b9cb539c | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Skyscrapers {
static int[][] rowHighestValue;
static int[][] colHighestValue;
static int[] colMax;
static int[] rowMax;
static int[][] board;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
rowHighestValue = new int[N][M];
colHighestValue = new int[N][M];
colMax = new int[M];
rowMax = new int[N];
board = new int[N][M];
for (int i = 0; i < N; i++) {
ArrayList<int[]> row = new ArrayList<>();
st = new StringTokenizer(f.readLine());
for (int j = 0; j < M; j++) {
int a = Integer.parseInt(st.nextToken());
row.add(new int[]{a, j});
board[i][j] = a;
}
Collections.sort(row, new Comparator<int[]>() {
@Override
public int compare(int[] ints, int[] t1) {
return Integer.compare(ints[0], t1[0]);
}
});
int count = 1;
rowHighestValue[i][row.get(0)[1]] = 1;
for (int j = 1; j < row.size(); j++) {
if (row.get(j)[0] != row.get(j-1)[0]) {
count++;
}
rowHighestValue[i][row.get(j)[1]] = count;
}
rowMax[i] = count;
}
for (int j = 0; j < M; j++) {
ArrayList<int[]> col = new ArrayList<>();
for (int i = 0; i < N; i++) {
col.add(new int[]{board[i][j], i});
}
Collections.sort(col, new Comparator<int[]>() {
@Override
public int compare(int[] ints, int[] t1) {
return Integer.compare(ints[0], t1[0]);
}
});
int count = 1;
colHighestValue[col.get(0)[1]][j] = 1;
for (int i = 1; i < col.size(); i++) {
if (col.get(i)[0] != col.get(i-1)[0]) {
count++;
}
colHighestValue[col.get(i)[1]][j] = count;
}
colMax[j] = count;
}
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int push = Math.max(colHighestValue[i][j], rowHighestValue[i][j]);
out.print(Math.max(colMax[j] + push - colHighestValue[i][j], rowMax[i] + push - rowHighestValue[i][j]) + " ");
}
out.println();
}
out.close();
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | a0c2957cf48553c08bcc505012b1f521 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
import java.util.jar.JarEntry;
public class Main {
public static void main(String[] args) throws Exception {
final FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = scanner.nextInt();
}
}
int[][] zipRow = new int[n][m];
int[] mxRow = new int[n];
Map<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
map.clear();
for (int j = 0; j < m; j++) {
map.put(a[i][j], 0);
}
int cur = -1;
int num = -1;
for (int j : map.keySet()) {
if (num != j) {
num = j;
cur++;
}
map.put(j, cur);
}
mxRow[i] = cur;
for (int j = 0; j < m; j++) {
zipRow[i][j] = map.get(a[i][j]);
}
}
int[][] zipCol = new int[m][n];
int[] mxCol = new int[m];
for (int i = 0; i < m; i++) {
map.clear();
for (int j = 0; j < n; j++) {
map.put(a[j][i], 0);
}
int cur = -1;
int num = -1;
for (int j : map.keySet()) {
if (num != j) {
num = j;
cur++;
}
map.put(j, cur);
}
mxCol[i] = cur;
for (int j = 0; j < n; j++) {
zipCol[i][j] = map.get(a[j][i]);
}
}
PrintWriter pw = new PrintWriter(System.out, false);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m ;j++) {
int my = Math.max(zipRow[i][j], zipCol[j][i]);
int bigger = Math.max(mxRow[i] - zipRow[i][j], mxCol[j] - zipCol[j][i]);
pw.print(my + bigger + 1 + " ");
}
pw.println();
}
pw.flush();
}
final static class FastScanner implements AutoCloseable {
private final int BUFFER_CAPACITY = 1024;
private final InputStream stream;
private final byte[] buffer = new byte[BUFFER_CAPACITY];
private int size = 0;
private int current = 0;
private char lastReadedChar = '\0';
FastScanner(InputStream stream) {
this.stream = stream;
}
public void close() throws Exception {
stream.close();
}
boolean hasNextLine() throws Exception {
try {
return Character.isWhitespace(lastReadedChar) || !endOfInputReached();
} catch (IOException e) {
return false;
}
}
char nextChar() throws Exception {
byte firstByte = nextByte();
int octets = 0;
for (int i = 7; (firstByte >> i & 1) == 1; i--) {
octets++;
}
if (octets == 0) {
return (char) firstByte;
}
char res = 0;
for (int bit = 7 - octets; bit >= 0; bit--) {
res <<= 1;
res += (firstByte >> bit) & 1;
}
for (int i = 1; i < octets; i++) {
res <<= 6;
res += nextByte() + 128;
}
return res;
}
String next() throws Exception {
do {
lastReadedChar = nextChar();
} while (Character.isWhitespace(lastReadedChar));
StringBuilder res = new StringBuilder();
while (!endOfInputReached() && !Character.isWhitespace(lastReadedChar)) {
res.append(lastReadedChar);
lastReadedChar = nextChar();
}
if (!Character.isWhitespace(lastReadedChar)) {
res.append(lastReadedChar);
}
return res.toString();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
private byte nextByte() throws Exception {
if (endOfInputReached()) {
throw new Exception();
}
return buffer[current++];
}
private void fillBuffer() throws Exception {
do {
size = stream.read(buffer);
} while (size == 0);
current = 0;
}
private boolean endOfInputReached() throws Exception {
if (current >= size) {
fillBuffer();
}
return size == -1;
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 5f619e83e7c92e7803c061365e0625b0 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
static class Task {
int NN = 200005;
int MOD = 1000000007;
int INF = 2000000000;
long INFINITY = 2000000000000000000L;
public void solve(InputReader in, PrintWriter out) {
int n= in.nextInt();
int m = in.nextInt();
int [][]a = new int[n + 1][m + 1];
int [][]cl = new int[n + 1][m + 1];
int [][]cg = new int[n + 1][m + 1];
int [][]rl = new int[n + 1][m + 1];
int [][]rg = new int[n + 1][m + 1];
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
a[i][j] = in.nextInt();
}
}
for(int j=1;j<=m;++j) {
Map<Integer, Integer> mp = new TreeMap<>();
for(int i=1;i<=n;++i) {
mp.put(a[i][j], 0);
}
int index =0;
for(int k:mp.keySet()) {
mp.put(k, ++index);
}
for(int i=1;i<=n;++i) {
cl[i][j] = mp.get(a[i][j]) - 1;
cg[i][j] = mp.size() - mp.get(a[i][j]);
}
}
for(int i=1;i<=n;++i) {
Map<Integer, Integer> mp = new TreeMap<>();
for(int j=1;j<=m;++j) {
mp.put(a[i][j], 0);
}
int index =0;
for(int k:mp.keySet()) {
mp.put(k, ++index);
}
for(int j=1;j<=m;++j) {
rl[i][j] = mp.get(a[i][j]) - 1;
rg[i][j] = mp.size() - mp.get(a[i][j]);
}
}
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
int lesser= Math.max(cl[i][j], rl[i][j]);
int target = lesser + 1;
int greater = Math.max(cg[i][j], rg[i][j]);
target += greater;
out.print(target + " ");
}
out.println();
}
}
}
static void prepareIO(boolean isFileIO) {
//long t1 = System.currentTimeMillis();
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
//out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
//fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 3017dc50f7d50fa38588d79998c0c9bb | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
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);
CSkyscrapers solver = new CSkyscrapers();
solver.solve(1, in, out);
out.close();
}
static class CSkyscrapers {
private int n;
private int m;
private int[][] arr;
private int[][] rankH;
private int[][] rankV;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
arr = new int[n + 1][m + 1];
rankH = new int[n + 1][m + 1];
rankV = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
int[][] temp = new int[m + 1][3];
for (int j = 1; j <= m; j++) {
arr[i][j] = in.nextInt();
temp[j][0] = arr[i][j];
temp[j][1] = j;
}
Arrays.sort(temp, Comparator.comparingInt(o -> o[0]));
temp[1][2] = 1;
int maxRank = temp[1][2];
for (int j = 2; j <= m; j++) {
if (temp[j - 1][0] == temp[j][0]) temp[j][2] = temp[j - 1][2];
else temp[j][2] = temp[j - 1][2] + 1;
maxRank = Math.max(maxRank, temp[j][2]);
}
for (int j = 1; j <= m; j++) {
rankH[i][temp[j][1]] = temp[j][2];
}
rankH[i][0] = maxRank;
}
for (int j = 1; j <= m; j++) {
int[][] temp = new int[n + 1][3];
for (int i = 1; i <= n; i++) {
temp[i][0] = arr[i][j];
temp[i][1] = i;
}
Arrays.sort(temp, Comparator.comparingInt(o -> o[0]));
temp[1][2] = 1;
int maxRank = temp[1][2];
for (int i = 2; i <= n; i++) {
if (temp[i - 1][0] == temp[i][0]) temp[i][2] = temp[i - 1][2];
else temp[i][2] = temp[i - 1][2] + 1;
maxRank = Math.max(maxRank, temp[i][2]);
}
for (int i = 1; i <= n; i++) {
rankV[temp[i][1]][j] = temp[i][2];
}
rankV[0][j] = maxRank;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int maxV = rankV[0][j], maxH = rankH[i][0];
int rankHorizontal = rankH[i][j], rankVertical = rankV[i][j];
if (rankHorizontal < rankVertical) {
out.printsc(Math.max(maxH + rankVertical - rankHorizontal, maxV));
} else {
out.printsc(Math.max(maxH, maxV + rankHorizontal - rankVertical));
}
}
out.println();
}
out.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public InputReader(FileInputStream file) {
this.stream = file;
}
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 = (res << 3) + (res << 1) + c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class OutputWriter {
private final PrintWriter writer;
private ArrayList<String> res = new ArrayList<>();
private StringBuilder sb = new StringBuilder("");
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
sb.append(objects[i]);
}
res.add(sb.toString());
sb = new StringBuilder("");
}
public void printsc(Object... objects) {
for (int i = 0; i < objects.length; i++) {
sb.append(objects[i]).append(' ');
}
}
public void close() {
writer.close();
}
public void flush() {
for (String str : res) writer.printf("%s\n", str);
res.clear();
sb = new StringBuilder("");
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 8cb4730c51a9950f4ce1294af0994bc4 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author /\
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] hor = new int[n][m];
int[][] vert = new int[n][m];
int[] horSz = new int[n];
int[] vertSz = new int[m];
for (int i = 0; i < n; i++) {
hor[i] = in.nextIntArray(m);
vert[i] = Arrays.copyOf(hor[i], m);
}
for (int i = 0; i < n; i++) {
int[] horTemp = Arrays.copyOf(hor[i], m);
Arrays.sort(horTemp);
Map<Integer, Integer> rank = new HashMap<>();
int temp = 1;
rank.put(horTemp[0], temp);
for (int j = 1; j < m; j++) {
rank.put(horTemp[j], horTemp[j] == horTemp[j - 1] ? temp : ++temp);
}
for (int j = 0; j < m; j++) {
hor[i][j] = rank.get(hor[i][j]);
}
horSz[i] = rank.keySet().size();
}
for (int i = 0; i < m; i++) {
int[] vertTemp = new int[n];
for (int j = 0; j < n; j++) {
vertTemp[j] = vert[j][i];
}
Arrays.sort(vertTemp);
Map<Integer, Integer> rank = new HashMap<>();
int temp = 1;
rank.put(vertTemp[0], temp);
for (int j = 1; j < n; j++) {
rank.put(vertTemp[j], vertTemp[j] == vertTemp[j - 1] ? temp : ++temp);
}
for (int j = 0; j < n; j++) {
vert[j][i] = rank.get(vert[j][i]);
}
vertSz[i] = rank.keySet().size();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (hor[i][j] >= vert[i][j]) {
sb.append(Math.max(horSz[i], hor[i][j] + vertSz[j] - vert[i][j]));
sb.append(" ");
} else {
sb.append(Math.max(vertSz[j], vert[i][j] + horSz[i] - hor[i][j]));
sb.append(" ");
}
}
sb.append("\n");
}
out.println(sb);
}
}
static class Scanner {
private StringTokenizer st;
private BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 6a204c10825b0a783fdfd59adab31d97 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import javafx.util.Pair;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Math.abs;
public class problem1 {
boolean ONLINE_JUDGE = (System.getProperty("ONLINE_JUDGE") != null);
public problem1() throws IOException {
InputReader in;
if (ONLINE_JUDGE) {
in = new InputReader(System.in);
} else {
in = new InputReader(new FileInputStream("input.txt"));
}
PrintWriter out = new PrintWriter(System.out);
int T = 1;
for (int caseNo = 1; caseNo <= T; caseNo++) {
solve(caseNo, in, out);
}
out.close();
}
int lower_bound(int arr[], int key, int low, int high)
{
if (low > high)
//return -1;
return low;
int mid = low + ((high - low) >> 1);
//if (arr[mid] == key) return mid;
//Attention here, we go left for lower_bound when meeting equal values
if (arr[mid] >= key)
return lower_bound(arr, key, low, mid - 1);
else
return lower_bound(arr, key, mid + 1, high);
}
private void solve(int caseNo, InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt(), m = in.nextInt();
int arr[][] = new int[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
arr[i][j] = in.nextInt();
}
}
Integer uniq_h[][] = new Integer[n][], uniq_v[][] = new Integer[m][];
for (int i = 0; i < n; ++i) {
Set<Integer> s = new TreeSet<>();
for (int j = 0; j < m; ++j) {
s.add(arr[i][j]);
}
uniq_h[i] = new Integer[s.size()];
s.toArray(uniq_h[i]);
}
for (int i = 0; i < m; ++i) {
Set<Integer> s = new TreeSet<>();
for (int j = 0; j < n; ++j) {
s.add(arr[j][i]);
}
uniq_v[i] = new Integer[s.size()];
s.toArray(uniq_v[i]);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int val = arr[i][j];
int h = Arrays.binarySearch(uniq_h[i], val);
int v = Arrays.binarySearch(uniq_v[j], val);
int ans = max(h, v) + max(uniq_h[i].length - h, uniq_v[j].length - v);
out.print(ans + " ");
}
out.println();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public String next() {
return nextString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public Long nextLong() {
return Long.parseLong(nextString());
}
public Double nextDouble() {
return Double.parseDouble(nextString());
}
public char nextCharacter() {
return nextString().charAt(0);
}
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 double[] nextDoubleArray(int N) {
double A[] = new double[N];
for (int i = 0; i < N; i++) {
A[i] = nextDouble();
}
return A;
}
}
int min(int... a) {
int min = Integer.MAX_VALUE;
for (int v : a) {
min = Math.min(min, v);
}
return min;
}
long min(long... a) {
long min = Long.MAX_VALUE;
for (long v : a) {
min = Math.min(min, v);
}
return min;
}
double min(double... a) {
double min = Double.MAX_VALUE;
for (double v : a) {
min = Math.min(min, v);
}
return min;
}
int max(int... a) {
int max = Integer.MIN_VALUE;
for (int v : a) {
max = Math.max(max, v);
}
return max;
}
long max(long... a) {
long max = Long.MIN_VALUE;
for (long v : a) {
max = Math.max(max, v);
}
return max;
}
double max(double... a) {
double max = Double.MIN_VALUE;
for (double v : a) {
max = Math.max(max, v);
}
return max;
}
private void debug(Object... o) {
if (ONLINE_JUDGE) {
return;
}
System.out.println(Arrays.deepToString(o));
}
public static void main(String args[]) throws IOException {
new problem1();
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | e97dbd74e6e08bd33d178fd70d72e1ba | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Comparator;
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);
C solver = new C();
solver.solve(1, in, out);
out.close();
}
static class C {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni(), m = in.ni();
final int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = in.ni();
}
}
int[][] rows = new int[n][m];
int[] rowMax = new int[n];
for (int i = 0; i < n; i++) {
Integer[] idx = new Integer[m];
for (int j = 0; j < m; j++) {
idx[j] = j;
}
final int[] row = map[i];
Arrays.sort(idx, Comparator.comparingInt(o -> row[o]));
int id = 0;
rows[i][idx[0]] = id;
for (int j = 1; j < m; j++) {
if (map[i][idx[j]] > map[i][idx[j - 1]]) {
rows[i][idx[j]] = ++id;
} else
rows[i][idx[j]] = id;
}
rowMax[i] = id;
}
int[][] cols = new int[n][m];
int[] colMax = new int[m];
for (int i = 0; i < m; i++) {
Integer[] idx = new Integer[n];
for (int j = 0; j < n; j++) {
idx[j] = j;
}
final int cur = i;
Arrays.sort(idx, Comparator.comparingInt(o -> map[o][cur]));
int id = 0;
cols[idx[0]][i] = id;
for (int j = 1; j < n; j++) {
if (map[idx[j]][i] > map[idx[j - 1]][i]) {
cols[idx[j]][i] = ++id;
} else
cols[idx[j]][i] = id;
}
colMax[i] = id;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int lessc = cols[i][j];
int lessr = rows[i][j];
int mid = Math.max(lessc, lessr) + 1;
out.print((mid + Math.max(colMax[j] - lessc, rowMax[i] - lessr)) + " ");
}
out.println();
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
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 ni() {
return Integer.parseInt(ns());
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 74e36793e50545ae8be99270a0be4275 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedInputStream;
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.Arrays;
import java.util.StringTokenizer;
public class C {
public void solve(JS in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
grid[i][j] = in.nextInt();
}
}
int[][] rowunder = new int[n][m];
int[][] rowover = new int[n][m];
int[][] colunder = new int[n][m];
int[][] colover = new int[n][m];
for(int i = 0; i < n; ++i) {
int[] aa = new int[m];
for(int j = 0; j < m; ++j) aa[j] = grid[i][j];
Arrays.sort(aa);
int unique = 1;
for(int j = 1; j < m; ++j) if(aa[j] != aa[j - 1]) ++unique;
int[] a = new int[unique];
a[0] = aa[0];
int idx = 1;
for(int j = 1; j < m; ++j) if(aa[j] != aa[j - 1]) {
a[idx++] = aa[j];
}
for(int j = 0; j < m; ++j) {
int x = grid[i][j];
int lo = 0, hi = unique - 1;
while(lo <= hi) {
int mi = lo + hi >> 1;
if(a[mi] >= x) hi = mi - 1;
else lo = mi + 1;
}
rowunder[i][j] = lo;
lo = 0; hi = unique - 1;
while(lo <= hi) {
int mi = lo + hi >> 1;
if(a[mi] <= x) lo = mi + 1;
else hi = mi - 1;
}
rowover[i][j] = unique - hi - 1;
}
}
for(int j = 0; j < m; ++j) {
int[] aa = new int[n];
for(int i = 0; i < n; ++i) aa[i] = grid[i][j];
Arrays.sort(aa);
int unique = 1;
for(int i = 1; i < n; ++i) if(aa[i] != aa[i - 1]) ++unique;
int[] a = new int[unique];
a[0] = aa[0];
int idx = 1;
for(int i = 1; i < n; ++i) if(aa[i] != aa[i - 1]) {
a[idx++] = aa[i];
}
for(int i = 0; i < n; ++i) {
int x = grid[i][j];
int lo = 0, hi = unique - 1;
while(lo <= hi) {
int mi = lo + hi >> 1;
if(a[mi] >= x) hi = mi - 1;
else lo = mi + 1;
}
colunder[i][j] = lo;
lo = 0; hi = unique - 1;
while(lo <= hi) {
int mi = lo + hi >> 1;
if(a[mi] <= x) lo = mi + 1;
else hi = mi - 1;
}
colover[i][j] = unique - hi - 1;
}
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(j != 0) out.print(" ");
int cur = Math.max(colunder[i][j], rowunder[i][j]) + Math.max(rowover[i][j], colover[i][j]) + 1;
out.print(cur);
}
out.println();
}
}
public static void main(String[] args) {
JS in = new JS();
PrintWriter out = new PrintWriter(System.out);
new C().solve(in, out);
out.close();
}
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() {
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;
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
//#
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
//$
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 66853468902aa8396d7ec67055fd6a1f | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
long[][] hts = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
hts[i][j] = in.nextLong();
int[][] rowLevels = new int[n][m];
int[][] colLevels = new int[n][m];
int[] rowTops = new int[n];
int[] colTops = new int[m];
for (int i = 0; i < n; i++) {
int row = i;
int[] indexes = radixSort(m, x -> hts[row][x]);
int level = 0;
long prevValue = 0;
for (int j = 0; j < m; j++) {
if (hts[row][indexes[j]] > prevValue) {
level++;
prevValue = hts[row][indexes[j]];
}
rowLevels[row][indexes[j]] = level;
}
rowTops[row] = level;
}
for (int i = 0; i < m; i++) {
int col = i;
int[] indexes = radixSort(n, x -> hts[x][col]);
int level = 0;
long prevValue = 0;
for (int j = 0; j < n; j++) {
if (hts[indexes[j]][col] > prevValue) {
level++;
prevValue = hts[indexes[j]][col];
}
colLevels[indexes[j]][col] = level;
}
colTops[col] = level;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sb.append(Math.max(rowLevels[i][j], colLevels[i][j]) + Math.max(rowTops[i] - rowLevels[i][j], colTops[j] - colLevels[i][j]));
sb.append(' ');
}
sb.append('\n');
}
System.out.println(sb);
}
interface LongFunction {
long get(int index);
}
private static int[] radixSort(int size, LongFunction extractor) {
int[] arr0 = new int[size];
int[] arr1 = new int[size];
int[] counts = new int[257];
for (int i = 0; i < size; i++) {
arr0[i] = i;
}
for (int i = 0; i < 64; i += 8) {
for (int j = 0; j < 256; j++) {
counts[j] = 0;
}
for (int j = 0; j < size; j++) {
long value = extractor.get(arr0[j]);
int key = (int) ((value >> i) % 256);
counts[key]++;
}
counts[256] = size;
for (int j = 255; j >= 0; j--) {
counts[j] = counts[j + 1] - counts[j];
}
for (int j = 0; j < size; j++) {
long value = extractor.get(arr0[j]);
int key = (int) ((value >> i) % 256);
arr1[counts[key]++] = arr0[j];
}
int[] arr = arr1;
arr1 = arr0;
arr0 = arr;
}
return arr0;
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | fe6295e36957eaf1a2ea08387b255cff | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 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 nC {
public class Pair implements Comparable<Pair> {
int x, i;
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return x - o.x;
}
}
public void run() throws NumberFormatException, IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int n = nextInt();
int m = nextInt();
int[][] mat = new int[n][m];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
mat[i][j] = nextInt();
}
}
Pair[][] x = new Pair[n][m];
Pair[][] y = new Pair[m][n];
Pair[][] xN = new Pair[n][m];
Pair[][] yN = new Pair[m][n];
int[] xM = new int[n];
int[] yM = new int[m];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
x[i][j] = new Pair();
x[i][j].x = mat[i][j];
x[i][j].i = j;
y[j][i] = new Pair();
y[j][i].x = mat[i][j];
y[j][i].i = i;
}
}
for (int i = 0; i < x.length; i++) {
Arrays.sort(x[i]);
int xx = 1;
xN[i][x[i][0].i] = new Pair();
xN[i][x[i][0].i].x = 1;
xN[i][x[i][0].i].i = x[i][0].i;
for (int j = 1; j < x[i].length; j++) {
if (x[i][j].x != x[i][j - 1].x) {
xx++;
}
xN[i][x[i][j].i] = new Pair();
xN[i][x[i][j].i].x = xx;
xN[i][x[i][j].i].i = x[i][j].i;
}
xM[i] = xx;
}
for (int i = 0; i < y.length; i++) {
Arrays.sort(y[i]);
int yy = 1;
yN[i][y[i][0].i] = new Pair();
yN[i][y[i][0].i].x = 1;
yN[i][y[i][0].i].i = y[i][0].i;
for (int j = 1; j < y[i].length; j++) {
if (y[i][j].x != y[i][j - 1].x) {
yy++;
}
yN[i][y[i][j].i] = new Pair();
yN[i][y[i][j].i].x = yy;
yN[i][y[i][j].i].i = y[i][j].i;
}
yM[i] = yy;
}
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
if(xN[i][j] == yN[j][i]) {
pw.print(Math.max(xM[i], yM[j]) + " ");
}else if(xN[i][j].x > yN[j][i].x) {
pw.print(Math.max(xM[i], yM[j] + xN[i][j].x - yN[j][i].x) + " ");
}else {
pw.print(Math.max(xM[i] - xN[i][j].x + yN[j][i].x, yM[j]) + " ");
}
}
pw.println("");
}
pw.close();
}
StringTokenizer st;
BufferedReader br;
PrintWriter pw;
public static void main(String[] args) throws IOException {
new nC().run();
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | cb6412314d53f935a64c01b993f14210 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class E1066 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver1066D solver = new Solver1066D();
solver.solve(inp, out);
out.close();
}
static class InputReader {
StringTokenizer tokenizer;
InputStreamReader sReader;
BufferedReader reader;
InputReader(InputStream stream) {
sReader = new InputStreamReader(stream);
reader = new BufferedReader(sReader, 32768);
tokenizer = null;
}
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 List<Integer> intLine(int size) {
List<Integer> ls = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
ls.add(nextInt());
}
return ls;
}
int nextC() {
try {
return reader.read();
} catch (IOException e) {
return -1;
}
}
public int[] intArr(int size) {
int[] ls = new int[size];
for (int i = 0; i < size; i++) ls[i] = nextInt();
return ls;
}
}
static class Solver1066D {
int[][] grid;
int[][] rowo, colo;
int[] row, col;
public void solve(InputReader inp, PrintWriter out) {
int n = inp.nextInt(), m = inp.nextInt(), i,j;
grid = new int[n][m];
rowo = new int[n][m];
colo = new int[m][n];
row = new int[n];
col = new int[m];
for (i = 0; i < n; i++){
grid[i] = inp.intArr(m);
}
for (i=0; i < n; i++){
HashSet<Integer> s = new HashSet<>();
for (j=0;j<m;j++) s.add(grid[i][j]);
ArrayList<Integer> distinct = new ArrayList<>(s);
Collections.sort(distinct);
HashMap<Integer, Integer> hm = new HashMap<>();
for (j=0; j < distinct.size(); j++)hm.put(distinct.get(j), j);
for (j=0; j<m;j++) rowo[i][j] = hm.get(grid[i][j]);
row[i] = distinct.size()-1;
}
for (j =0; j<m;j++){
HashSet<Integer> s = new HashSet<>();
for (i=0;i<n;i++) s.add(grid[i][j]);
ArrayList<Integer> distinct = new ArrayList<>(s);
Collections.sort(distinct);
HashMap<Integer, Integer> hm = new HashMap<>();
for (i=0;i<distinct.size();i++) hm.put(distinct.get(i),i);
for (i=0;i<n;i++) colo[j][i] = hm.get(grid[i][j]);
col[j] = distinct.size()-1;
}
for (i=0;i<n;i++){
for (j=0;j<m;j++) {
int val = Math.max(rowo[i][j], colo[j][i]) + Math.max(row[i] - rowo[i][j], col[j] - colo[j][i]);
out.print(val + 1 + " ");
}
out.println();
}
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 9e9307a9e659c3082623f354441f22a5 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class E1066 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver1066D solver = new Solver1066D();
solver.solve(inp, out);
out.close();
}
static class InputReader {
StringTokenizer tokenizer;
InputStreamReader sReader;
BufferedReader reader;
InputReader(InputStream stream) {
sReader = new InputStreamReader(stream);
reader = new BufferedReader(sReader, 32768);
tokenizer = null;
}
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 List<Integer> intLine(int size) {
List<Integer> ls = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
ls.add(nextInt());
}
return ls;
}
int nextC() {
try {
return reader.read();
} catch (IOException e) {
return -1;
}
}
public ArrayList<Integer> intArr(int size) {
ArrayList<Integer> ls = new ArrayList<>(size);
for (int i = 0; i < size; i++){
ls.add(i, nextInt());
}
return ls;
}
}
static class Solver1066D {
ArrayList<ArrayList<Integer>> grid;
int[][] rowo, colo;
int[] row, col;
public void solve(InputReader inp, PrintWriter out) {
int n = inp.nextInt(), m = inp.nextInt(), i,j;
grid = new ArrayList<>(n);
rowo = new int[n][m];
colo = new int[m][n];
row = new int[n];
col = new int[m];
for (i = 0; i < n; i++){
grid.add(i, inp.intArr(m));
}
for (i=0; i < n; i++){
rowo[i] = new int[m];
ArrayList<Integer> distinct = new ArrayList<>(new HashSet<>(grid.get(i)));
Collections.sort(distinct);
HashMap<Integer, Integer> hm = new HashMap<>();
for (j=0; j < distinct.size(); j++){
hm.put(distinct.get(j), j);
}
for (j=0; j<m;j++){
rowo[i][j] = hm.get(grid.get(i).get(j));
}
row[i] = distinct.size()-1;
}
for (j =0; j<m;j++){
HashSet<Integer> s = new HashSet<>();
for (i=0;i<n;i++) s.add(grid.get(i).get(j));
ArrayList<Integer> distinct = new ArrayList<>(s);
Collections.sort(distinct);
HashMap<Integer, Integer> hm = new HashMap<>();
for (i=0;i<distinct.size();i++) hm.put(distinct.get(i),i);
for (i=0;i<n;i++) {
colo[j][i] = hm.get(grid.get(i).get(j));
}
col[j] = distinct.size()-1;
}
for (i=0;i<n;i++){
for (j=0;j<m;j++) {
int val = Math.max(rowo[i][j], colo[j][i]) + Math.max(row[i] - rowo[i][j], col[j] - colo[j][i]);
out.print(val + 1 + " ");
}
out.println();
}
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | ab6831005a3eac357dd7500ce3d8aee7 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.util.*;
public class scratch_25 {
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next());
}
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n= Reader.nextInt();
int m= Reader.nextInt();
int arr[][]= new int[n][m];
int arr1[][]= new int[n][m];
int arr2[][]= new int[m][n];
int max1[]= new int[n];
int max2[]= new int[m];
StringBuilder str= new StringBuilder();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 0; i <n ; i++) {
for (int j = 0; j <m ; j++) {
arr[i][j]= Reader.nextInt();
arr1[i][j]= arr[i][j];
}
}
// System.out.println("arr=");
// // System.out.println(Arrays.toString(arr));
// for (int i = 0; i <n ; i++) {
// System.out.println(Arrays.toString(arr[i]));
// }
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr2[i][j] = arr[j][i];
}
}
for (int i = 0; i < n; i++) {
// sort(arr1[i], 0, m - 1);
int end = arr.length;
Set<Integer> set = new HashSet<Integer>();
for (int j = 0; j < m; j++) {
set.add(arr1[i][j]);
}
TreeSet<Integer> t= new TreeSet<Integer>(set);
int f = set.size();
max1[i] = f;
Arrays.fill(arr1[i], Integer.MAX_VALUE);
Iterator it = t.iterator();
int count = 0;
while (it.hasNext()) {
arr1[i][count] = (int) it.next();
count++;
}
// System.out.println(f);
// System.out.println(removeDuplicates(arr1[i],m));
// System.out.println(Arrays.toString(arr1[i]));
}
for (int i = 0; i < m; i++) {
// sort(arr2[i], 0, n - 1);
Set<Integer> set = new HashSet<Integer>();
for (int j = 0; j < n; j++) {
set.add(arr2[i][j]);
}
int f = set.size();
TreeSet<Integer> t = new TreeSet<Integer>(set);
max2[i] = f;
Arrays.fill(arr2[i], Integer.MAX_VALUE);
Iterator it = t.iterator();
int count = 0;
while (it.hasNext()) {
arr2[i][count] = (int) it.next();
count++;
}
// System.out.println(f);
// removeDuplicates(arr2[i],n);
}
// System.out.println("arr1=");
// for (int i = 0; i <n ; i++) {
// System.out.println(Arrays.toString(arr1[i]));
// }
// System.out.println("arr2=");
// for (int i = 0; i <m ; i++) {
// System.out.println(Arrays.toString(arr2[i]));
// }
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int u = arr[i][j];
int res1 = Arrays.binarySearch(arr1[i], u);
int res2 = Arrays.binarySearch(arr2[j], u);
// System.out.println("res1="+res1);
// System.out.println("res2="+res2);
// HashSet<Integer> hm = new HashSet<Integer>();
// for (int k = 0; k <res1 ; k++) {
// hm.add(arr1[i][k]);
// }
int low1 = res1;
// HashSet<Integer> hs = new HashSet<Integer>();
// for (int k = 0; k <res2 ; k++) {
// hs.add(arr2[j][k]);
// }
int low2 = res2;
// HashSet<Integer> ha = new HashSet<Integer>();
// for (int k = res1; k <m ; k++) {
// ha.add(arr1[i][k]);
// }
int high1 = max1[i] - res1 - 1;
// HashSet<Integer> hb = new HashSet<Integer>();
// for (int k = res2; k <n ; k++) {
// // System.out.println("bhosdike");
// hb.add(arr2[j][k]);
// }
int high2 = max2[j] - res2 - 1;
int l = Math.max(low1, low2) + 1 + Math.max(high1, high2);
out.write(l + " ");
}
out.write("\n");
}
// System.out.println("ans=");
out.close();
}
static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
static boolean ans(int check, long arr[],int n,int med,int k){
long ans=0;
for (int i = med; i <n ; i++) {
if(check>=arr[i]){
ans+=check-arr[i];
}
}
return ans<=k;
}
static long smallestDivisor(long n)
{
// if divisible by 2
if (n % 2 == 0)
return 2;
// iterate from 3 to sqrt(n)
for (int i = 3; (long)i *(long) i <= n; i += 2) {
if (n % i == 0)
return i;
}
return n;
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static BigDecimal fd(int mid, double h, double c){
BigDecimal a = new BigDecimal((h+c)/(2.0));
BigDecimal b = new BigDecimal((h-c)/(2.0*mid));
BigDecimal cd = a.add(b);
return cd;
}
static int partition(double arr[],int arr1[],int arr2[], int low, int high)
{
double pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++;
// swap arr[i] and arr[j]
double temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
int temp1=arr1[i];
arr1[i]=arr1[j];
arr1[j]=temp1;
int temp2=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp2;
}
}
// swap arr[i+1] and arr[high] (or pivot)
double temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
int temp1= arr1[i+1];
arr1[i+1]=arr1[high];
arr1[high]= temp1;
int temp2= arr2[i+1];
arr2[i+1]=arr2[high];
arr2[high]= temp2;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(double arr[],int arr1[],int arr2[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr,arr1,arr2, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr,arr1,arr2, low, pi-1);
sort(arr,arr1, arr2,pi+1, high);
}
}
static int removeDuplicates(int arr[], int n)
{
// Return, if array is empty
// or contains a single element
if (n==0 || n==1)
return n;
int[] temp = new int[n];
// Start traversing elements
int j = 0;
for (int i=0; i<n-1; i++)
// If current element is not equal
// to next element then store that
// current element
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];
// Modify original array
for (int i=0; i<j; i++)
arr[i] = temp[i];
return j;
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 7973b6088449fdb1387fd649b9bff093 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class A implements Runnable {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt(), m = scn.nextInt();
int[][] arr = scn.next2DInt(n, m);
int[][] row = new int[n][m];
int[] maxR = new int[n];
for (int i = 0; i < n; i++) {
int[] a = new int[m];
for (int j = 0; j < m; j++) {
a[j] = arr[i][j];
}
a = compress(a);
int max = 0;
for (int j = 0; j < m; j++) {
row[i][j] = a[j];
max = Math.max(max, row[i][j]);
}
maxR[i] = max;
}
int[][] col = new int[n][m];
int[] maxC = new int[m];
for (int j = 0; j < m; j++) {
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = arr[i][j];
}
a = compress(a);
int max = 0;
for(int i = 0; i < n; i++) {
col[i][j] = a[i];
max = Math.max(max, col[i][j]);
}
maxC[j] = max;
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int ans;
if(row[i][j] < col[i][j]) {
ans = Math.max(maxR[i] + col[i][j] - row[i][j], maxC[j]);
} else if(col[i][j] < row[i][j]) {
ans = Math.max(maxR[i], maxC[j] + row[i][j] - col[i][j]);
} else {
ans = Math.max(maxR[i], maxC[j]);
}
out.print(ans + " ");
}
out.println();
}
}
int[] compress(int[] arr) {
int n = arr.length;
int[] copy = Arrays.copyOf(arr, n);
copy = scn.uniq(copy);
for (int i = 0; i < n; i++) {
arr[i] = 1 + Arrays.binarySearch(copy, arr[i]);
}
return arr;
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new A(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | b29113051bb9f160e9663d631595d3d6 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeSet;
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;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader sc, PrintWriter out) {
int n=sc.nextInt();
int m=sc.nextInt();
int[][] map=new int[n+1][m+1];
int[][] col=new int[m+1][n+1];
int[][] row=new int[n+1][m+1];
int[] x=new int[n+1]; //ζ―θ‘ε
η΄ δΈͺζ°
int[] y=new int[m+1]; //ζ―εε
η΄ δΈͺζ°
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
map[i][j]=sc.nextInt();
}
}
for(int i=1;i<=n;i++) {
TreeSet<Integer> set=new TreeSet<Integer>();
HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();
for(int j=1;j<=m;j++)
set.add(map[i][j]);
int index=0;
x[i]=set.size();
for(int val:set) {
hash.put(val,++index);
}
for(int j=1;j<=m;j++) {
row[i][j]=hash.get(map[i][j]);
}
}
for(int i=1;i<=m;i++) {
TreeSet<Integer> set=new TreeSet<Integer>();
HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();
for(int j=1;j<=n;j++)
set.add(map[j][i]);
int index=0;
y[i]=set.size();
for(int val:set) {
hash.put(val,++index);
}
for(int j=1;j<=n;j++) {
col[i][j]=hash.get(map[j][i]);
}
}
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
int ans;
if(row[i][j]>col[j][i])
ans=Math.max(row[i][j]+y[j]-col[j][i], x[i]);
else
if(col[j][i]>row[i][j])
ans=Math.max(col[j][i]+x[i]-row[i][j],y[j]);
else
ans=Math.max(x[i], y[j]);
out.print(ans+" ");
}
out.println();
}
}
}
static class Node implements Comparable<Node>{
int index;
int val;
public Node(int index,int val) {
this.index=index;
this.val=val;
}
@Override
public int compareTo(Node o) {
return this.val-o.val;
}
}
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());
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 160c2a27228477b6aa3d47a0e50eee0a | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Main {
static class Pair implements Comparable<Pair> {
int idx, value;
public Pair(int idx, int value) {
this.idx = idx;
this.value = value;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(value, o.value);
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = sc.nextInt();
}
}
int[][][] info = new int[4][n][m];
// 0=>sv, 1=>sh, 2=>lv, 3=>lh
for (int j = 0; j < m; j++) {
Pair[] pairs = new Pair[n];
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(i, a[i][j]);
}
Arrays.sort(pairs);
int smaller = -1, last = -1;
for (int i = 0; i < n; i++) {
if(pairs[i].value != last) {
last = pairs[i].value;
smaller++;
}
info[0][pairs[i].idx][j] = smaller;
}
}
for (int i = 0; i < n; i++) {
Pair[] pairs = new Pair[m];
for (int j = 0; j < m; j++) {
pairs[j] = new Pair(j, a[i][j]);
}
Arrays.sort(pairs);
int smaller = -1, last = -1;
for (int j = 0; j < m; j++) {
if(pairs[j].value != last) {
last = pairs[j].value;
smaller++;
}
info[1][i][pairs[j].idx] = smaller;
}
}
for (int j = 0; j < m; j++) {
Pair[] pairs = new Pair[n];
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(i, a[i][j]);
}
Arrays.sort(pairs);
int smaller = -1, last = -1;
for (int i = n - 1; i >= 0; i--) {
if(pairs[i].value != last) {
last = pairs[i].value;
smaller++;
}
info[2][pairs[i].idx][j] = smaller;
}
}
for (int i = 0; i < n; i++) {
Pair[] pairs = new Pair[m];
for (int j = 0; j < m; j++) {
pairs[j] = new Pair(j, a[i][j]);
}
Arrays.sort(pairs);
int smaller = -1, last = -1;
for (int j = m - 1; j >= 0; j--) {
if(pairs[j].value != last) {
last = pairs[j].value;
smaller++;
}
info[3][i][pairs[j].idx] = smaller;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(j > 0) out.print(" ");
out.print(Math.max(info[0][i][j], info[1][i][j]) +
Math.max(info[2][i][j], info[3][i][j]) + 1);
}
out.println();
}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader fileReader) {
br = new BufferedReader(fileReader);
}
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());
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 3a83ad484b65b4aa0f22c7048e473476 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class C {
// ------------------------
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// ------------------------
int n=sc.nextInt(),m=sc.nextInt();
int[][]grid=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
grid[i][j]=sc.nextInt();
int[][]indHor=new int[n][m];
int[]sHor=new int[n];
for(int i=0;i<n;i++){
TreeSet<Integer>nums=new TreeSet<Integer>();
for(int j=0;j<m;j++)
nums.add(grid[i][j]);
sHor[i]=nums.size();
ArrayList<Integer>a=new ArrayList<Integer>();
while(!nums.isEmpty())
a.add(nums.pollFirst());
for(int j=0;j<m;j++)
indHor[i][j]=Collections.binarySearch(a,grid[i][j]);
}
int[][]indVer=new int[n][m];
int[]sVer=new int[m];
for(int j=0;j<m;j++){
TreeSet<Integer>nums=new TreeSet<Integer>();
for(int i=0;i<n;i++)
nums.add(grid[i][j]);
sVer[j]=nums.size();
ArrayList<Integer>a=new ArrayList<Integer>();
while(!nums.isEmpty())
a.add(nums.pollFirst());
for(int i=0;i<n;i++)
indVer[i][j]=Collections.binarySearch(a,grid[i][j]);
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int ind=Math.max(indVer[i][j],indHor[i][j]);
out.print(Math.max(sHor[i]+ind-indHor[i][j],sVer[j]+ind-indVer[i][j])+" ");
}
out.println();
}
// ------------------------
out.close();
}
//------------------------
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 50dbfdcd0e7b69fdd495989ed7e643c4 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes |
import java.io.*;
import java.util.*;
public class Sol {
static class FastReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextLine() 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();
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long mod = (long)(1e9+7);
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
// TODO Auto-generated method stub
int n = sc.nextInt();
int m = sc.nextInt();
int tab[][] = new int[n][m];
int A[][] = new int[n][m];
int B[][] = new int[n][m];
int C[][] = new int[n][m];
int D[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tab[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n; i++) {
ArrayList<Integer> str = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int j = 0; j < m; j++) {
if (!set.contains(tab[i][j])) {
str.add(tab[i][j]);
set.add(tab[i][j]);
}
}
Collections.sort(str);
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int j = 0; j < str.size(); j++) {
map.put(str.get(j), j);
}
for (int j = 0; j < m; j++) {
A[i][j] = str.size() - map.get(tab[i][j]) - 1;
B[i][j] = map.get(tab[i][j]);
}
}
for (int j = 0; j < m; j++) {
ArrayList<Integer> stl = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
if (!set.contains(tab[i][j])) {
stl.add(tab[i][j]);
set.add(tab[i][j]);
}
}
Collections.sort(stl);
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < stl.size(); i++) {
map.put(stl.get(i), i);
}
for (int i = 0; i < n; i++) {
C[i][j] = stl.size() - map.get(tab[i][j]) - 1;
D[i][j] = map.get(tab[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(1 + Math.max(A[i][j], C[i][j]) + Math.max(D[i][j], B[i][j]) + " ");
}
out.println();
}
out.close();
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 5f1db53588fa5a701ba45b8b869c14d0 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
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);
CNeboskrebi solver = new CNeboskrebi();
solver.solve(1, in, out);
out.close();
}
static class CNeboskrebi {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int h = 0; h < m; h++) {
a[i][h] = in.nextInt();
}
}
List<Pair<Integer, Integer>> hs = new ArrayList<>();
for (int i = 0; i < m; i++) {
hs.add(new Pair<>(0, 0));
}
int[] pos = new int[m];
int[][] rPos = new int[n][m];
int[] rUnique = new int[n];
for (int i = 0; i < n; i++) {
for (int h = 0; h < m; h++) {
hs.get(h).fs = a[i][h];
hs.get(h).sc = h;
}
rUnique[i] = uniqueAndPos(hs, pos);
for (int h = 0; h < m; h++) {
rPos[i][h] = pos[h];
}
}
hs = new ArrayList<>();
for (int i = 0; i < n; i++) {
hs.add(new Pair<>(0, 0));
}
pos = new int[n];
int[][] cPos = new int[n][m];
int[] cUnique = new int[m];
for (int i = 0; i < m; i++) {
for (int h = 0; h < n; h++) {
hs.get(h).fs = a[h][i];
hs.get(h).sc = h;
}
cUnique[i] = uniqueAndPos(hs, pos);
for (int h = 0; h < n; h++) {
cPos[h][i] = pos[h];
}
}
for (int i = 0; i < n; i++) {
for (int h = 0; h < m; h++) {
int max = Math.max(rPos[i][h], cPos[i][h]);
int rMax = rUnique[i];
if (max > rPos[i][h]) {
rMax += max - rPos[i][h];
}
int cMax = cUnique[h];
if (max > cPos[i][h]) {
cMax += max - cPos[i][h];
}
out.print(Math.max(rMax, cMax));
out.print(' ');
}
out.println();
}
}
private int uniqueAndPos(List<Pair<Integer, Integer>> hs, int[] pos) {
hs.sort(Comparator.comparingInt(a -> a.fs));
int unique = 1;
pos[hs.get(0).sc] = 1;
for (int i = 1; i < hs.size(); i++) {
if (!hs.get(i).fs.equals(hs.get(i - 1).fs)) {
unique++;
}
pos[hs.get(i).sc] = unique;
}
return unique;
}
}
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());
}
}
static class Pair<T, K> {
T fs;
K sc;
public Pair(T fs, K sc) {
this.fs = fs;
this.sc = sc;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | e9fae5b6c37689d35384321a72ce4788 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L;
static final int INf = 1_000_000_000;
static FastReader reader;
static PrintWriter writer;
public static void main(String[] args) {
Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
t.start();
}
static class O implements Runnable {
public void run() {
try {
magic();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(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[1000000];
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();
}
}
static int map[];
static void magic() throws IOException{
reader = new FastReader();
writer = new PrintWriter(System.out, true);
int n = reader.nextInt(), m = reader.nextInt();
int mat[][] = new int[n][m];
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
mat[i][j] = reader.nextInt();
}
}
int virtual_row[][] = new int[n][m];
int max_in_row[] = new int[n];
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
virtual_row[i][j] = mat[i][j];
}
compress1(virtual_row[i], m);
for(int e : virtual_row[i]) {
max_in_row[i] = max(max_in_row[i], e);
}
}
// writer.println("Virtual row array: ");
// for(int i=0;i<n;++i) {
// for(int j=0;j<m;++j) {
// writer.print(virtual_row[i][j] + " ");
// }
// writer.println();
// }
int virtual_column[][] = new int[m][n];
int max_in_column[] = new int[m];
for(int COL=0;COL<m;++COL) {
for(int i=0;i<n;++i) {
virtual_column[COL][i] = mat[i][COL];
}
compress1(virtual_column[COL], n);
for(int e : virtual_column[COL]) {
max_in_column[COL] = max(max_in_column[COL], e);
}
}
// writer.println("Virtual col array: ");
// for(int i=0;i<m;++i) {
// for(int j=0;j<n;++j) {
// writer.print(virtual_column[i][j] + " ");
// }
// writer.println();
// }
StringBuilder fast = new StringBuilder();
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
int assign_by_row = virtual_row[i][j];
int assign_by_col = virtual_column[j][i];
// writer.println("i: "+i+" j: "+j);
// writer.println("assign by row: "+assign_by_row);
// writer.println("assign by col: "+assign_by_col);
if(assign_by_row>assign_by_col) {
int ans = max(max_in_row[i], max_in_column[j] + (assign_by_row - assign_by_col));
fast.append(ans);
if(j<m-1) {
fast.append(" ");
}
}
else {
int ans = max(max_in_row[i] + (assign_by_col - assign_by_row), max_in_column[j]);
fast.append(ans);
if(j<m-1) {
fast.append(" ");
}
}
}
fast.append("\n");
}
writer.print(fast);
writer.flush();
}
static void compress1(int arr[],int n)
{
int copy[] = new int[n];
for(int i=0;i<n;++i) {
copy[i] = arr[i];
}
Arrays.sort(arr);
Map<Integer, Integer> map = new HashMap<>();
int dis_cnt = 1;
for(int i=0;i<n;++i) {
map.put(arr[i], dis_cnt);
while(i+1<n && arr[i+1]==arr[i]) {
i++;
}
dis_cnt++;
}
for(int i=0;i<n;++i) {
arr[i] = map.get(copy[i]);
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | b1f5ec3b8d8121f929da2ca64d7d711b | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class c {
public c() {
FS scan = new FS();
PrintWriter out = new PrintWriter(System.out);
int r = scan.nextInt(), c = scan.nextInt();
int[][] grid = new int[r][c];
int[][] maxrow = new int[r][c];
int[][] maxcol = new int[r][c];
int[][] posrow = new int[r][c];
int[][] poscol = new int[r][c];
for(int i = 0 ; i < r ; i++) {
for(int j = 0 ; j < c ; j++) {
grid[i][j] = scan.nextInt();
}
}
for(int i = 0 ; i < r ; i++) { // look at each row
TreeSet<Integer> order = new TreeSet<>();
for(int j = 0 ; j < c ; j++) order.add(grid[i][j]);
TreeMap<Integer, Integer> inds = new TreeMap<>();
for(int vals : order) inds.put(vals, inds.size() + 1);
for(int j = 0 ; j < c ; j++) {
maxrow[i][j] = order.size();
posrow[i][j] = inds.get(grid[i][j]);
}
}
for(int j = 0 ; j < c ; j++) { // look at each row
TreeSet<Integer> order = new TreeSet<>();
for(int i = 0 ; i < r ; i++) order.add(grid[i][j]);
TreeMap<Integer, Integer> inds = new TreeMap<>();
for(int vals : order) inds.put(vals, inds.size() + 1);
for(int i = 0 ; i < r ; i++) {
maxcol[i][j] = order.size();
poscol[i][j] = inds.get(grid[i][j]);
}
}
for(int i = 0 ; i < r ; i++) {
for(int j = 0 ; j < c ; j++) {
if(posrow[i][j] > poscol[i][j]) {
int dif = posrow[i][j] - poscol[i][j];
out.printf("%d ", Math.max(maxrow[i][j], maxcol[i][j] + dif));
}
if(posrow[i][j] < poscol[i][j]) {
int dif = poscol[i][j] - posrow[i][j];
out.printf("%d ", Math.max(maxrow[i][j] + dif, maxcol[i][j]));
}
if(posrow[i][j] == poscol[i][j]) {
out.printf("%d ", Math.max(maxrow[i][j], maxcol[i][j]));
}
}
out.println();
}
out.close();
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while(!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
}
public static void main(String[] args) { new c(); }
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 0d19b6e948e744124378d777ded16abc | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.stream.Stream;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
CSkyscrapers solver = new CSkyscrapers();
solver.solve(1, in, out);
out.close();
}
static class CSkyscrapers {
public void solve(int testNumber, LightScanner in, LightWriter out) {
int n = in.ints(), m = in.ints();
int[][] a = in.ints(n, m);
int[] cs = new int[m], ce = new int[n];
int[][] s = new int[n][m], e = new int[n][m];
Vec2i[] vs = new Vec2i[n];
for (int i = 0; i < n; i++) {
vs[i] = new Vec2i(0, 0);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
vs[j].x = j;
vs[j].y = a[j][i];
}
IntroSort.sort(vs, Comparator.comparing(v -> v.y));
int c = 0;
for (int j = 0; j < n; j++) {
if (j != 0 && vs[j - 1].y != vs[j].y) {
c++;
}
s[vs[j].x][i] = c;
}
cs[i] = c + 1;
}
vs = new Vec2i[m];
for (int i = 0; i < m; i++) {
vs[i] = new Vec2i(0, 0);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
vs[j].x = j;
vs[j].y = a[i][j];
}
IntroSort.sort(vs, Comparator.comparing(v -> v.y));
int c = 0;
for (int j = 0; j < m; j++) {
if (j != 0 && vs[j - 1].y != vs[j].y) {
c++;
}
e[i][vs[j].x] = c;
}
ce[i] = c + 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int lo = Math.max(s[i][j], e[i][j]);
int hi = Math.max(cs[j] - s[i][j] - 1, ce[i] - e[i][j] - 1);
out.ans(lo + hi + 1);
}
out.ln();
}
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public int[] ints(int length) {
return IntStream.range(0, length).map(x -> ints()).toArray();
}
public int[][] ints(int height, int width) {
return IntStream.range(0, height).mapToObj(x -> ints(width)).toArray(int[][]::new);
}
}
static class IntroSort {
private static int INSERTIONSORT_THRESHOLD = 16;
private IntroSort() {
}
static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) {
while (high - low > INSERTIONSORT_THRESHOLD) {
if (maxDepth-- == 0) {
HeapSort.sort(a, low, high, comparator);
return;
}
int cut = QuickSort.step(a, low, high, comparator);
sort(a, cut, high, maxDepth, comparator);
high = cut;
}
InsertionSort.sort(a, low, high, comparator);
}
public static <T> void sort(T[] a, Comparator<T> comparator) {
if (a.length <= INSERTIONSORT_THRESHOLD) {
InsertionSort.sort(a, 0, a.length, comparator);
} else {
sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);
}
}
}
static class QuickSort {
private QuickSort() {
}
private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) {
if (comparator.compare(a[z], a[x]) < 0) {
ArrayUtil.swap(a, low, x);
} else if (comparator.compare(a[y], a[z]) < 0) {
ArrayUtil.swap(a, low, y);
} else {
ArrayUtil.swap(a, low, z);
}
}
static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) {
int x = low + 1, y = low + (high - low) / 2, z = high - 1;
if (comparator.compare(a[x], a[y]) < 0) {
med(a, low, x, y, z, comparator);
} else {
med(a, low, y, x, z, comparator);
}
int lb = low + 1, ub = high;
while (true) {
while (comparator.compare(a[lb], a[low]) < 0) {
lb++;
}
ub--;
while (comparator.compare(a[low], a[ub]) < 0) {
ub--;
}
if (lb >= ub) {
return lb;
}
ArrayUtil.swap(a, lb, ub);
lb++;
}
}
}
static final class BitMath {
private BitMath() {
}
public static int count(int v) {
v = (v & 0x55555555) + ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);
v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);
v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);
return v;
}
public static int msb(int v) {
if (v == 0) {
throw new IllegalArgumentException("Bit not found");
}
v |= (v >> 1);
v |= (v >> 2);
v |= (v >> 4);
v |= (v >> 8);
v |= (v >> 16);
return count(v) - 1;
}
}
static interface Verified {
}
static class InsertionSort {
private InsertionSort() {
}
static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) {
for (int i = low; i < high; i++) {
for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {
ArrayUtil.swap(a, j - 1, j);
}
}
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(int i) {
return ans(Integer.toString(i));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static class HeapSort {
private HeapSort() {
}
private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) {
int child = 2 * i - low + 1;
while (child < high) {
if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {
child++;
}
if (comparator.compare(val, a[child]) >= 0) {
break;
}
a[i] = a[child];
i = child;
child = 2 * i - low + 1;
}
a[i] = val;
}
static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) {
for (int p = (high + low) / 2 - 1; p >= low; p--) {
heapfy(a, low, high, p, a[p], comparator);
}
while (high > low) {
high--;
T pval = a[high];
a[high] = a[low];
heapfy(a, low, high, low, pval, comparator);
}
}
}
static class Vec2i implements Comparable<Vec2i> {
public int x;
public int y;
public Vec2i(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vec2i vec2i = (Vec2i) o;
return x == vec2i.x && y == vec2i.y;
}
public int hashCode() {
return 31 * x + y;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public int compareTo(Vec2i o) {
if (x == o.x) {
return Integer.compare(y, o.y);
}
return Integer.compare(x, o.x);
}
}
static final class ArrayUtil {
private ArrayUtil() {
}
public static <T> void swap(T[] a, int x, int y) {
T t = a[x];
a[x] = a[y];
a[y] = t;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 4939fb525c88af843d2ea07b95f23f61 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.*;
import java.util.*;
public class Source {
static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream){
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()){
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException ignored){}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args){
FastScanner scanner = new FastScanner(System.in);
PrintWriter printer = new PrintWriter(System.out);
int n = scanner.nextInt(), m = scanner.nextInt();
int[][] a = new int[n][m];
int[][] b = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = scanner.nextInt();
b[j][i] = a[i][j];
}
}
ArrayList<Map<Integer, Integer>>hLowerThan = new ArrayList<>(n);
ArrayList<Map<Integer, Integer>>vLowerThan = new ArrayList<>(m);
int[][] hSorted = new int[n][];
int[][] vSorted = new int[m][];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < (k == 0 ? n : m); i++) {
Map<Integer, Integer> l = new HashMap<>();
int []sorted;
if (k == 0) {
hLowerThan.add(l);
hSorted[i] = Arrays.stream(a[i]).distinct().sorted().toArray();
sorted = hSorted[i];
}
else {
vLowerThan.add(l);
vSorted[i] = Arrays.stream(b[i]).distinct().sorted().toArray();
sorted = vSorted[i];
}
l.put(sorted[0], 0);
for (int j = 1; j < sorted.length; j++) {
l.put(sorted[j], l.get(sorted[j-1]) + 1);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int k1 = Math.max(hLowerThan.get(i).get(a[i][j]), vLowerThan.get(j).get(a[i][j]));
int k2 = Math.max(hSorted[i].length - hLowerThan.get(i).get(a[i][j]) - 1, vSorted[j].length - vLowerThan.get(j).get(a[i][j]) - 1);
printer.print(k1 + k2 + 1 + " ");
}
printer.println();
}
printer.flush();
printer.close();
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | e1e8347a16fe0498e9344f2e571ccc53 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
import java.util.TreeMap;
import java.util.Map;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author xwchen
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] row = new int[n][m];
int[][] col = new int[n][m];
int[] mxrow = new int[n];
int[] mxcol = new 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] = in.nextInt();
}
}
for (int i = 0; i < n; ++i) {
TreeSet<Integer> set = new TreeSet<>();
for (int j = 0; j < m; ++j) {
set.add(a[i][j]);
}
Map<Integer, Integer> map = new TreeMap<>();
int cnt = 1;
for (int v : set) {
map.put(v, cnt++);
}
for (int j = 0; j < m; ++j) {
row[i][j] = map.get(a[i][j]);
mxrow[i] = Math.max(mxrow[i], row[i][j]);
}
}
for (int j = 0; j < m; ++j) {
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < n; ++i) {
set.add(a[i][j]);
}
Map<Integer, Integer> map = new TreeMap<>();
int cnt = 1;
for (int v : set) {
map.put(v, cnt++);
}
for (int i = 0; i < n; ++i) {
col[i][j] = map.get(a[i][j]);
mxcol[j] = Math.max(mxcol[j], col[i][j]);
}
}
int[][] ans = new int[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int mrow = mxrow[i];
int mcol = mxcol[j];
int r = row[i][j];
int c = col[i][j];
if (r == c) {
ans[i][j] = Math.max(mrow, mcol);
} else if (r > c) {
int diff = r - c;
ans[i][j] = Math.max(mrow, mcol + diff);
} else {
int diff = c - r;
ans[i][j] = Math.max(mrow + diff, mcol);
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
out.print(ans[i][j] + " ");
}
}
}
}
static class InputReader {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream in;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public InputReader(InputStream inputStream) {
this.in = new DataInputStream(inputStream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() {
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;
}
private void fillBuffer() {
try {
bytesRead = in.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
} catch (IOException e) {
throw new InputMismatchException();
}
}
private byte read() {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 8fd4fe38a233d28b313decb3ecc2ab57 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class SkyScrapers {
static class Pos {
int nBig;
int nSmall;
int mBig;
int mSmall;
}
static class Pair {
int val;
int pos;
Pair(int x, int y) {
this.val = x;
this.pos = y;
}
}
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
int n = Integer.parseInt(stringTokenizer.nextToken());
int m = Integer.parseInt(stringTokenizer.nextToken());
int[][] board = new int[n][m];
BufferedOutputStream bout = new BufferedOutputStream(System.out);
for (int i = 0; i < n; i++) {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
for (int j = 0; j < m; j++) {
board[i][j] = Integer.parseInt(stringTokenizer.nextToken());
}
}
List<Pair> elems = new ArrayList<>();
Pos[][] pos = new Pos[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
pos[i][j] = new Pos();
}
}
for (int i = 0; i < m; i++) {
elems.add(new Pair(0, 0));
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
elems.set(j, new Pair(board[i][j], j));
}
elems.sort(Comparator.comparingInt(a -> a.val));
int rank = 1;
pos[i][elems.get(0).pos].nSmall = rank - 1;
for (int j = 1; j < m; j++) {
if (elems.get(j).val > elems.get(j - 1).val) {
rank++;
}
pos[i][elems.get(j).pos].nSmall = rank - 1;
}
for (int j = 0; j < m; j++) {
pos[i][j].nBig = rank - pos[i][j].nSmall - 1;
}
}
elems.clear();
for (int i = 0; i < n; i++) {
elems.add(new Pair(1, 2));
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
elems.set(j, new Pair(board[j][i], j));
}
elems.sort(Comparator.comparingInt(a -> a.val));
int rank = 1;
pos[elems.get(0).pos][i].mSmall = rank - 1;
for (int j = 1; j < n; j++) {
if (elems.get(j).val > elems.get(j - 1).val) {
rank++;
}
pos[elems.get(j).pos][i].mSmall = rank - 1;
}
for (int j = 0; j < n; j++) {
pos[j][i].mBig = rank - pos[j][i].mSmall - 1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
String s = (Math.max(pos[i][j].nSmall, pos[i][j].mSmall) + 1 + Math.max(pos[i][j].mBig, pos[i][j].nBig) + " ");
bout.write(s.getBytes());
}
bout.write('\n');
}
bout.flush();
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 43cfb4a626c3cd93bc2c6741c84f4d74 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.SplittableRandom;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
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;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CSkyscrapers solver = new CSkyscrapers();
solver.solve(1, in, out);
out.close();
}
static class CSkyscrapers {
public void solve(int testNumber, FastReader in, PrintWriter out) {
// Debug debug = new Debug();
int n = in.nextInt();
int m = in.nextInt();
int[][] map = in.nextIntMap(n, m);
int[][] max = new int[n][m];
ArrayUtils.fill(max, 1);
for (int i = 0; i < n; ++i) {
int[] row = map[i];
int[] a = Arrays.copyOf(row, row.length);
a = ArrayUtils.sort(a);
a = ArrayUtils.uniqueArray(a);
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int aa : a) hashMap.put(aa, hashMap.size() + 1);
for (int j = 0; j < m; ++j) {
max[i][j] = Math.max(max[i][j], hashMap.get(map[i][j]));
}
}
for (int i = 0; i < m; ++i) {
int[] a = new int[n];
for (int j = 0; j < n; ++j) a[j] = map[j][i];
a = ArrayUtils.sort(a);
a = ArrayUtils.uniqueArray(a);
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int aa : a) hashMap.put(aa, hashMap.size() + 1);
for (int j = 0; j < n; ++j) {
max[j][i] = Math.max(max[j][i], hashMap.get(map[j][i]));
}
}
// for (int[] mm : max) debug.tr(mm);
int[][] ans = new int[n][m];
for (int i = 0; i < n; ++i) {
int[] row = map[i];
int[] a = Arrays.copyOf(row, row.length);
a = ArrayUtils.sort(a);
a = ArrayUtils.uniqueArray(a);
// debug.tr(a);
for (int j = 0; j < m; ++j) {
int ind = Arrays.binarySearch(a, map[i][j]);
ans[i][j] = Math.max(ans[i][j], max[i][j] + a.length - ind - 1);
}
// debug.tr(add[i]);
// debug.tr("--------------------");
}
for (int j = 0; j < m; ++j) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) a[i] = map[i][j];
a = ArrayUtils.sort(a);
a = ArrayUtils.uniqueArray(a);
// debug.tr(a);
for (int i = 0; i < n; ++i) {
int ind = Arrays.binarySearch(a, map[i][j]);
ans[i][j] = Math.max(ans[i][j], max[i][j] + a.length - ind - 1);
}
// int[] aa = new int[n];
// for (int i = 0;i < n; ++i) aa[i] = add[i][j];
// debug.tr(aa);
// debug.tr("--------------------");
}
ArrayUtils.printMap(out, ans);
}
}
static class ArrayUtils {
public static int[] sort(int[] a) {
a = shuffle(a, new SplittableRandom());
Arrays.sort(a);
return a;
}
public static int[] shuffle(int[] a, SplittableRandom gen) {
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
public static int[] uniqueArray(int[] a) {
int n = a.length;
int p = 0;
for (int i = 0; i < n; i++) {
if (i == 0 || a[i] != a[i - 1]) a[p++] = a[i];
}
return Arrays.copyOf(a, p);
}
public static void printArray(PrintWriter out, int[] array) {
if (array.length == 0) return;
for (int i = 0; i < array.length; i++) {
if (i != 0) out.print(" ");
out.print(array[i]);
}
out.println();
}
public static void printMap(PrintWriter out, int[][] map) {
for (int i = 0; i < map.length; i++) {
printArray(out, map[i]);
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public int[][] nextIntMap(int n, int m) {
int[][] array = new int[n][];
for (int i = 0; i < n; i++) {
array[i] = nextIntArray(m);
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | f5a2112e525c444b72b2c4ef574fe89f | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author toshif
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyReader in = new MyReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, MyReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] x = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
x[i][j] = in.nextInt();
}
}
int[][] cl = new int[n][m];
int[][] ch = new int[n][m];
int[][] rl = new int[n][m];
int[][] rh = new int[n][m];
search(x, cl, ch, n, m, false);
int[][] x2 = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
x2[j][i] = x[i][j];
}
}
search(x2, rl, rh, m, n, true);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print((Math.max(cl[i][j], rl[i][j]) + 1 + Math.max(ch[i][j], rh[i][j])) + " ");
}
out.println();
}
}
void search(int[][] x, int[][] cl, int[][] ch, int n, int m, boolean flip) {
for (int i = 0; i < n; i++) {
int[] a = x[i];
Set<Integer> s = new HashSet<>();
for (int j = 0; j < m; j++) {
s.add(a[j]);
}
ArrayList<Integer> as = new ArrayList<>(s);
Collections.sort(as);
for (int j = 0; j < m; j++) {
int idx = Collections.binarySearch(as, a[j]);
if (!flip) {
cl[i][j] = idx;
ch[i][j] = as.size() - idx - 1;
} else {
cl[j][i] = idx;
ch[j][i] = as.size() - idx - 1;
}
}
}
}
}
static class MyReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 60fdce5c42dad67125361edcff95de94 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes |
/**
* Date: 8 Mar, 2019
* Link:
*
* @author Prasad-Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import java.util.PriorityQueue;
public class newProgram7 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
FastIO in = new FastIO();
int n = in.ni();
int m = in.ni();
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) {
a[i] = in.gia(m);
}
ArrayList<Map<Integer, Integer>> al_r = new ArrayList<>();
for (int i = 0; i < n; i++) {
al_r.add(new Hashtable<>());
}
int max_r[] = new int[n];
for (int i = 0; i < n; i++) {
PriorityQueue<Data> pq = new PriorityQueue<>();
for (int j = 0; j < m; j++) {
pq.add(new Data(a[i][j], j));
}
int index = 0;
while (!pq.isEmpty()) {
if (!al_r.get(i).containsKey(pq.peek().a)) {
al_r.get(i).put(pq.peek().a, index++);
}
pq.remove();
}
max_r[i] = index - 1;
}
int max_c[] = new int[m];
ArrayList<Map<Integer, Integer>> al_c = new ArrayList<>();
for (int i = 0; i < m; i++) {
al_c.add(new Hashtable<>());
}
for (int i = 0; i < m; i++) {
PriorityQueue<Data> pq = new PriorityQueue<>();
for (int j = 0; j < n; j++) {
pq.add(new Data(a[j][i], j));
}
int index = 0;
while (!pq.isEmpty()) {
Data d = pq.remove();
if (!al_c.get(i).containsKey(d.a)) {
al_c.get(i).put(d.a, index++);
}
}
max_c[i] = index - 1;
}
int ans[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int rep_r = al_r.get(i).get(a[i][j]);
int rep_c = al_c.get(j).get(a[i][j]);
if (rep_r == rep_c) {
ans[i][j] = Math.max(max_c[j], max_r[i]);
} else if (rep_r < rep_c) {
ans[i][j] = Math.max(max_r[i] + rep_c - rep_r, max_c[j]);
} else {
ans[i][j] = Math.max(max_r[i], max_c[j] + rep_r - rep_c);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
in.print((ans[i][j] + 1) + " ");
}
in.println("");
}
in.bw.flush();
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
private StringBuilder sb;
public FastIO() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
s = br.readLine().split(" ");
sb = new StringBuilder();
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nl();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = nl();
}
return a;
}
public int[][][] gwtree(int n) throws IOException {
int m = n - 1;
int adja[][] = new int[n + 1][];
int weight[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
int cost[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = i + 1;
to[i] = ni();
cost[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
weight[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][count[from[i]] - 1] = to[i];
adja[to[i]][count[to[i]] - 1] = from[i];
weight[from[i]][count[from[i]] - 1] = cost[i];
weight[to[i]][count[to[i]] - 1] = cost[i];
count[from[i]]--;
count[to[i]]--;
}
return new int[][][]{adja, weight};
}
public int[][][] gwg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int weight[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
int cost[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
cost[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
weight[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][count[from[i]] - 1] = to[i];
adja[to[i]][count[to[i]] - 1] = from[i];
weight[from[i]][count[from[i]] - 1] = cost[i];
weight[to[i]][count[to[i]] - 1] = cost[i];
count[from[i]]--;
count[to[i]]--;
}
return new int[][][]{adja, weight};
}
public int[][] gtree(int n) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[n - 1];
int to[] = new int[n - 1];
int count[] = new int[n + 1];
for (int i = 0; i < n - 1; i++) {
from[i] = i + 1;
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < n - 1; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public int[][] gg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public void print(String s) throws IOException {
bw.write(s);
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a == o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
public static void sort(int a[]) {
Data d[] = new Data[a.length];
for (int i = 0; i < a.length; i++) {
d[i] = new Data(a[i], 0);
}
Arrays.sort(d);
for (int i = 0; i < a.length; i++) {
a[i] = d[i].a;
}
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 339cf0c663d9c2b5ed2240a5150ab0e3 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Task
{
public static void solve() throws Exception
{
int rowsNum = scanner.nextInt();
int columnsNum = scanner.nextInt();
List<List<Integer>> rows = new ArrayList<>(rowsNum);
List<List<Integer>> columns = new ArrayList<>(columnsNum);
for(int j=0;j<columnsNum;j++) {
columns.add(new ArrayList<Integer>(rowsNum));
}
for(int i=0;i<rowsNum;i++) {
List<Integer> row = new ArrayList<Integer>(columnsNum);
for(int j=0;j<columnsNum;j++) {
int v = scanner.nextInt();
row.add(v);
List<Integer> column = columns.get(j);
column.add(v);
}
rows.add(row);
}
List<Integer> rowMax = new ArrayList<>(rows.size());
for(List<Integer> list: rows) {
int size = updateList(list);
rowMax.add(size);
}
List<Integer> columnMax = new ArrayList<>(columns.size());
for(List<Integer> list: columns) {
int size = updateList(list);
columnMax.add(size);
}
StringBuilder sb = new StringBuilder(rowsNum * columnsNum * 4);
for(int i=0;i<rowsNum;i++) {
for(int j=0;j<columnsNum;j++) {
int maxRow = rowMax.get(i);
int maxCol = columnMax.get(j);
int rowInd = rows.get(i).get(j);
int colInd = columns.get(j).get(i);
if(rowInd > colInd) {
maxCol += rowInd - colInd;
} else if(rowInd < colInd) {
maxRow += colInd - rowInd;
}
int ret = Math.max(maxRow, maxCol);
if(j > 0) {
sb.append(" ");
}
sb.append(+ret);
}
sb.append("\n");
}
System.out.print(sb.toString());
}
private static int updateList(List<Integer> list) {
List<Integer> cloned = new ArrayList<>(list.size());
cloned.addAll(list);
Collections.sort(cloned);
Map<Integer, Integer> val2ind = new HashMap<>(list.size());
int ind = 0;
for(Integer val: cloned) {
if(!val2ind.containsKey(val)) {
ind++;
val2ind.put(val, ind);
}
}
for(int i=0;i<list.size();i++) {
list.set(i, val2ind.get(list.get(i)));
}
return ind;
}
public static void main(String[] args) throws Exception
{
try
{
scanner = new Reader();//new Scanner(new BufferedInputStream(System.in));
systemOut = new BufferedOutputStream(System.out);
solve();
}
finally
{
scanner.close();
systemOut.close();
}
}
private static Reader scanner = null;
private static BufferedOutputStream systemOut = null;
public static void out(String str)
{
try
{
systemOut.write(str.getBytes("utf-8"));
}
catch(Exception ex)
{
throw new RuntimeException(ex);
}
}
public static void outln(String str)
{
out(str);
out("\n");
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String 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 | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 9a4906314f4e82cc7a7b5a1c049e109f | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
FastScanner in= new FastScanner(System.in);
PrintWriter out= new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
int [][] byrow = new int[n][m];
int [][] bycol = new int[n][m];
int [] maxrow = new int[n];
int [] maxcol = new int[m];
int [][] g= new int[n][m];
for (int i = 0; i < n; i++) {
Integer [] rr = new Integer[m];
for (int j = 0; j < m; j++) {
g[i][j] = in.nextInt();
rr[j]= g[i][j];
}
//do row cc
Arrays.sort(rr);
HashMap<Integer, Integer> hm = new HashMap<>();
int count = 1;
for (int j = 0; j < rr.length; j++) {
if(!hm.containsKey(rr[j])) {
hm.put(rr[j], count++);
}
}
for (int j = 0; j < rr.length; j++) {
byrow[i][j] = hm.get(g[i][j]);
}
maxrow[i] = count-1;
}
for (int i = 0; i < m; i++) {
Integer [] cc = new Integer[n];
for (int j = 0; j < n; j++) {
cc[j] = g[j][i];
}
//do column cc
Arrays.sort(cc);
HashMap<Integer, Integer> hm = new HashMap<>();
int count = 1;
for (int j = 0; j < cc.length; j++) {
if(!hm.containsKey(cc[j])) {
hm.put(cc[j], count++);
}
}
for (int j = 0; j < n; j++) {
bycol[j][i] = hm.get(g[j][i]);
}
maxcol[i] = count-1;
}
// for (int i = 0; i < m; i++) {
// System.out.println(maxcol[i]);
// }
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int res = 100000000;
if(bycol[i][j] == byrow[i][j]) {
res = Math.max(maxrow[i], maxcol[j]);
}
else if(byrow[i][j] < bycol[i][j]){
//take max of col
res = maxcol[j];
//and try taking difference required
int dif = bycol[i][j] - byrow[i][j];
int newval = maxrow[i] + dif;
res = Math.max(res, newval);
}
else {
//take max of row
res = maxrow[i];
//and try taking difference required
int dif = byrow[i][j] - bycol[i][j];
int newval = maxcol[j] + dif;
res = Math.max(res, newval);
}
out.print(res+ " ");
}
out.println();
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
return next();
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
/*
4 5
1 1 10 1 1
1 1 20 1 1
11 13 14 15 16
1 1 10 1 1
*/ | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | ef4ae835ab09e99b7b9348d2b8c8e6dd | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CSkyscrapers solver = new CSkyscrapers();
solver.solve(1, in, out);
out.close();
}
static class CSkyscrapers {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] tab = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tab[i][j] = sc.nextInt();
}
}
CSkyscrapers.Pair t;
HashMap<Integer, Integer> done = new HashMap<>();
ArrayList<CSkyscrapers.Pair> col = new ArrayList<>();
int[][] rankcol = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
t = new CSkyscrapers.Pair();
t.x = tab[j][i];
t.y = j;
col.add(t);
}
Collections.sort(col, new Comparator<CSkyscrapers.Pair>() {
public int compare(CSkyscrapers.Pair a, CSkyscrapers.Pair b) {
return Integer.compare(a.x, b.x);
}
});
int r = 0;
rankcol[col.get(0).y][i] = r;
for (int j = 1; j < col.size(); j++) {
if (col.get(j).x != col.get(j - 1).x)
r++;
rankcol[col.get(j).y][i] = r;
}
col.clear();
}
int[][] rankrow = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
t = new CSkyscrapers.Pair();
t.x = tab[i][j];
t.y = j;
col.add(t);
}
Collections.sort(col, new Comparator<CSkyscrapers.Pair>() {
public int compare(CSkyscrapers.Pair a, CSkyscrapers.Pair b) {
return Integer.compare(a.x, b.x);
}
});
int r = 0;
rankrow[i][col.get(0).y] = r;
for (int j = 1; j < col.size(); j++) {
if (col.get(j).x != col.get(j - 1).x)
r++;
rankrow[i][col.get(j).y] = r;
}
col.clear();
}
int[] maxrow = new int[n];
int max;
for (int i = 0; i < n; i++) {
max = 0;
for (int j = 0; j < m; j++) {
if (rankrow[i][j] > max) {
max = rankrow[i][j];
}
}
maxrow[i] = max;
}
int[] maxcol = new int[m];
for (int i = 0; i < m; i++) {
max = 0;
for (int j = 0; j < n; j++) {
if (rankcol[j][i] > max) {
max = rankcol[j][i];
}
}
maxcol[i] = max;
}
int[][] ans = new int[n][m];
int act;
int add;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
act = Math.max(rankcol[i][j], rankrow[i][j]);
add = Math.max(maxcol[j] - rankcol[i][j], maxrow[i] - rankrow[i][j]);
ans[i][j] = act + add;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print((ans[i][j] + 1) + " ");
}
out.println();
}
}
static class Pair {
int x;
int y;
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | b7ac00a78d3bad363765d208e1220cf8 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CSkyscrapers solver = new CSkyscrapers();
solver.solve(1, in, out);
out.close();
}
static class CSkyscrapers {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
int arr[][] = new int[n][m];
int row[][] = new int[n][];
int[][] col = new int[m][];
for (int i = 0; i < n; i++) {
HashSet<Integer> hs = new HashSet<>();
for (int j = 0; j < m; j++) {
arr[i][j] = in.scanInt();
hs.add(arr[i][j]);
}
row[i] = new int[hs.size()];
int u = 0;
for (int k : hs) {
row[i][u++] = k;
}
CodeX.sort(row[i]);
}
for (int j = 0; j < m; j++) {
HashSet<Integer> hs = new HashSet<>();
for (int i = 0; i < n; i++) {
hs.add(arr[i][j]);
}
col[j] = new int[hs.size()];
int u = 0;
for (int k : hs) {
col[j][u++] = k;
}
CodeX.sort(col[j]);
}
int ans[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int smallrow = CodeX.lbound(row[i], 0, row[i].length, arr[i][j]);
int smallcol = CodeX.lbound(col[j], 0, col[j].length, arr[i][j]);
int biggerrow = (row[i].length - smallrow - 1);
int biggercol = (col[j].length - smallcol - 1);
int seting = Math.max(smallcol, smallrow) + 1;
ans[i][j] = seting + Math.max(biggercol, biggerrow);
out.print(ans[i][j] + " ");
}
out.println();
}
}
}
static class CodeX {
public static int lbound(int array[], int l, int h, int x) {
while (l < h) {
int mid = (l + h) / 2;
if (array[mid] >= x) h = mid;
else l = mid + 1;
}
return l;
}
public static void sort(int arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(int A[], int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(int A[], int start, int mid, int end) {
int p = start, q = mid + 1;
int Arr[] = new int[end - start + 1];
int k = 0;
for (int i = start; i <= end; i++) {
if (p > mid)
Arr[k++] = A[q++];
else if (q > end)
Arr[k++] = A[p++];
else if (A[p] < A[q])
Arr[k++] = A[p++];
else
Arr[k++] = A[q++];
}
for (int i = 0; i < k; i++) {
A[start++] = Arr[i];
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 48c0abd3723076289bdc08221ab1ec92 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 megabytes | import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.round;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverse;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.comparingLong;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
solveC();
}
private void solveA() throws IOException {
int n = in.nextInt();
int[] t = new int[n];
for (int i = 0; i < n; i++)
t[i] = in.nextInt();
int ans = 0;
for (int l = 0, m = 0, r; l < n; l = m) {
while (m < n && t[l] == t[m])
m++;
r = m;
while (r < n && t[m] == t[r])
r++;
ans = max(ans, min(m - l, r - m));
}
out.println(ans * 2);
}
private void solveB() throws IOException {
int n = in.nextInt();
char[] c = in.next().toCharArray();
for (int i = 0; i < n; i++)
c[i] -= '0';
char[] a = in.next().toCharArray();
for (int i = 0; i < n; i++)
a[i] -= '0';
int[][] q = new int[4][n];
int[] ql = new int[4], qr = new int[4];
for (int i = 0; i < n; i++)
q[c[i] * 2 + a[i]][qr[c[i] * 2 + a[i]]++] = i;
int[] ans = new int[n / 2];
int s = 0;
while (qr[3] - ql[3] > 1) {
ans[s++] = q[3][ql[3]++];
ql[3]++;
}
if (qr[3] - ql[3] > 0) {
if (qr[2] - ql[2] > qr[1] - ql[1]) {
ans[s++] = q[2][ql[2]++];
ql[3]++;
} else if (qr[1] - ql[1] > 0) {
ans[s++] = q[3][ql[3]++];
ql[1]++;
}
}
while (qr[2] - ql[2] > 0 && qr[1] - ql[1] > 0) {
ans[s++] = q[2][ql[2]++];
ql[1]++;
}
while (qr[1] - ql[1] > 0 && qr[0] - ql[0] > 0) {
ans[s++] = q[1][ql[1]++];
ql[0]++;
}
while (qr[0] - ql[0] > 0 && qr[2] - ql[2] > 0) {
ans[s++] = q[0][ql[0]++];
ql[2]++;
}
while (qr[0] - ql[0] > 1) {
ans[s++] = q[0][ql[0]++];
ql[0]++;
}
if (s < n / 2)
out.print(-1);
else
for (int i = 0; i < s; i++)
out.print(ans[i] + 1 + " ");
}
private void solveC() throws IOException {
int n = in.nextInt(), m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
int[][] as = new int[n][m];
for (int i = 0; i < n; i++) {
System.arraycopy(a[i], 0, as[i], 0, m);
shuffle(as[i]);
sort(as[i]);
}
int[][] ars = new int[m][n];
int[][] mrs = new int[m][n];
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++)
ars[j][i] = a[i][j];
shuffle(ars[j]);
sort(ars[j]);
for (int i = 1; i < n; i++)
mrs[j][i] = ars[j][i - 1] == ars[j][i] ? mrs[j][i - 1] : mrs[j][i - 1] + 1;
}
int[] ms = new int[m];
for (int i = 0, pi, pj, mx; i < n; i++) {
for (int j = 1; j < m; j++)
ms[j] = as[i][j - 1] == as[i][j] ? ms[j - 1] : ms[j - 1] + 1;
for (int j = 0; j < m; j++) {
pj = Arrays.binarySearch(as[i], a[i][j]);
pi = Arrays.binarySearch(ars[j], a[i][j]);
mx = max(ms[pj], mrs[j][pi]);
out.print(max(ms[m - 1] + 1 + mx - ms[pj], mrs[j][n - 1] + 1 + mx - mrs[j][pi]) + " ");
}
out.println();
}
}
private void solveD() throws IOException {
String s = in.next();
int[] sCnt = new int[2];
for (int i = 0; i < s.length(); i++)
sCnt[s.charAt(i) - '0']++;
String t = in.next();
int m = t.length();
int[] tCnt = new int[2];
for (int i = 0; i < m; i++)
tCnt[t.charAt(i) - '0']++;
int pi[] = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && t.charAt(i) != t.charAt(j))
j = pi[j - 1];
if (t.charAt(i) == t.charAt(j))
j++;
pi[i] = j;
}
if (sCnt[0] >= tCnt[0] && sCnt[1] >= tCnt[1]) {
out.print(t);
sCnt[0] -= tCnt[0];
sCnt[1] -= tCnt[1];
fill(tCnt, 0);
for (int i = pi[m - 1]; i < m; i++)
tCnt[t.charAt(i) - '0']++;
t = t.substring(pi[m - 1]);
int min = min(tCnt[0] == 0 ? 1000000 : sCnt[0] / tCnt[0], tCnt[1] == 0 ? 1000000 : sCnt[1] / tCnt[1]);
for (int i = min; i > 0; i--)
out.print(t);
for (int i = sCnt[0] - min * tCnt[0]; i > 0; i--)
out.print('0');
for (int i = sCnt[1] - min * tCnt[1]; i > 0; i--)
out.print('1');
out.println();
} else {
out.println(s);
}
}
private void solveF() throws IOException{
}
private void shuffle(int[] a) {
int b;
Random r = new Random();
for (int i = a.length - 1, j; i > 0; i--) {
j = r.nextInt(i + 1);
b = a[j];
a[j] = a[i];
a[i] = b;
}
}
private class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
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();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | 1708d0aaafa4ae56b4bd7308ae68c664 | train_000.jsonl | 1552035900 | Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection. | 512 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 C_Round_545_Div2 {
public static long MOD = 998244353;
static long[][][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int m = in.nextInt();
int[][] data = new int[n][m];
HashSet<Integer>[] row = new HashSet[n];
HashSet<Integer>[] col = new HashSet[m];
for (int i = 0; i < n; i++) {
row[i] = new HashSet<>();
}
for (int i = 0; i < m; i++) {
col[i] = new HashSet<>();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = in.nextInt();
row[i].add(data[i][j]);
col[j].add(data[i][j]);
}
}
int[][] r = new int[n][];
int[][] c = new int[m][];
for (int i = 0; i < n; i++) {
r[i] = new int[row[i].size()];
int index = 0;
for (int j : row[i]) {
r[i][index++] = j;
}
Arrays.sort(r[i]);
}
for (int i = 0; i < m; i++) {
c[i] = new int[col[i].size()];
int index = 0;
for (int j : col[i]) {
c[i][index++] = j;
}
Arrays.sort(c[i]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int a = smaller(data[i][j], r[i]);
int b = r[i].length - a - 1;
int x = smaller(data[i][j], c[j]);
int y = c[j].length - x - 1;
int re = 1 + Integer.max(a, x) + Integer.max(b, y);
//System.out.println(data[i][j] + " " + Arrays.toString(r[i]) + " " + Arrays.toString(c[j]) + " " + a + " " + b + " " + x + " " + y);
out.print(re + " ");
}
out.println();
}
out.close();
}
static int smaller(int v, int[] data) {
int st = 0;
int ed = data.length - 1;
int re = 0;
while (st <= ed) {
int mid = (st + ed) / 2;
if (data[mid] < v) {
re = mid + 1;
st = mid + 1;
} else {
ed = mid - 1;
}
}
return re;
}
static int larger(int v, int st, int[] data) {
int ed = data.length - 1;
int re = 0;
while (st <= ed) {
int mid = (st + ed) / 2;
if (data[mid] > v) {
re = data.length - mid;
ed = mid - 1;
} else {
st = mid + 1;
}
}
return re;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | Java | ["2 3\n1 2 1\n2 1 2", "2 2\n1 2\n3 4"] | 2 seconds | ["2 2 2 \n2 2 2", "2 3 \n3 2"] | NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column | Java 8 | standard input | [
"implementation",
"sortings"
] | 206861107f0c06d3c8e358a85b9ddd7f | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction. | 1,600 | Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street. | standard output | |
PASSED | f6b4d3ca59b1f3b83508e4f559acaeb2 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | //package contests.CF1012;
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
int k = (n+1)/2;
arr = new int[n+1];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
dp = new int[3][k+2][n+1];
int inf = (int)1e9;
for (int i = 0; i < dp.length; i++)
for (int j = 0; j < dp[i].length; j++)
Arrays.fill(dp[i][j], -1);
for (int i = 1; i <= k; i++) {
pw.print(solve(0, i, NORM) + " ");
}
pw.flush();
pw.close();
}
static int dp[][][];
static int n;
static int BUILD = 2, DEM = 1, NORM = 0;
static int[] arr;
static int inf = (int)1e9;
static int solve(int idx, int h, int prev){
if(h == 0)
return 0;
if(idx == n)
return inf;
if(dp[prev][h][idx] != -1)
return dp[prev][h][idx];
int ans = inf;
// build
if(prev != BUILD){
int add = 0;
if(idx != 0){
int p = arr[idx-1];
if(prev == DEM && idx-2 >= 0)
p = Math.min(p, arr[idx-2]-1);
add = Math.max(0, p-arr[idx]+1);
}
if(idx != n-1)
add += Math.max(0, arr[idx+1]-arr[idx]+1);
ans = Math.min(ans, add + solve(idx+1, h-1, BUILD));
}
// leave
ans = Math.min(ans, solve(idx+1, h, NORM));
// demolish
if(prev == BUILD)
ans = Math.min(ans, solve(idx+1, h, DEM));
return dp[prev][h][idx] = ans;
}
static int[][] packD(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from) if(f != -1) p[f]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];}
return g;
}
static void shuffle(int[] a)
{
int n = a.length;
for(int i = 0; i < n; i++)
{
int r = i + (int)(Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(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 boolean ready() throws IOException {return br.ready();}
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | b2539a04b655c5b073eb6a934655af7c | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | //package contests.CF1012;
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
int k = (n+1)/2;
arr = new int[n+2];
for (int i = 1; i <= n; i++) {
arr[i] = sc.nextInt();
}
dp = new int[3][k+1][n+1];
for (int i = 0; i < dp.length; i++)
for (int j = 0; j < dp[i].length; j++)
Arrays.fill(dp[i][j], -1);
for (int i = 1; i <= k; i++) {
pw.print(solve(1, i, NORM) + " ");
}
pw.flush();
pw.close();
}
static int dp[][][];
static int n;
static int BUILD = 2, DEM = 1, NORM = 0;
static int[] arr;
static int inf = (int)1e9;
static int solve(int idx, int h, int prev){
if(h == 0)
return 0;
if(idx == n+1)
return inf;
if(dp[prev][h][idx] != -1)
return dp[prev][h][idx];
int ans = inf;
// build
if(prev != BUILD){
int p = arr[idx-1];
if(prev == DEM)
p = Math.min(p, arr[idx-2]-1);
ans = Math.min(ans, Math.max(0, p-arr[idx]+1) + Math.max(0, arr[idx+1]-arr[idx]+1) + solve(idx+1, h-1, BUILD));
}
// leave
ans = Math.min(ans, solve(idx+1, h, NORM));
// demolish
if(prev == BUILD)
ans = Math.min(ans, solve(idx+1, h, DEM));
return dp[prev][h][idx] = ans;
}
static int[][] packD(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from) if(f != -1) p[f]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];}
return g;
}
static void shuffle(int[] a)
{
int n = a.length;
for(int i = 0; i < n; i++)
{
int r = i + (int)(Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(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 boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 66c73a14bc9fc81c3d7c3628ee92efdb | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
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);
CHills solver = new CHills();
solver.solve(1, in, out);
out.close();
}
}
static class CHills {
public int dec(int x, int t) {
return x < t ? 0 : x - t + 1;
}
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int m = (n + 1) / 2;
int[][][] dp = new int[3][n + 1][m + 1];
int[] h = new int[n + 1];
for (int i = 1; i <= n; i++) {
h[i] = in.readInt();
}
h[0] = (int) -1e9;
int inf = (int) 1e9;
SequenceUtils.deepFill(dp, inf);
dp[1][0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
//build a house
if (j > 0) {
dp[0][i][j] = Math.min(dp[1][i - 1][j - 1] + dec(h[i - 1], h[i]), dp[0][i][j]);
if (i > 1) {
dp[0][i][j] = Math.min(dp[2][i - 1][j - 1] + dec(h[i - 2] - 1, h[i]),
dp[0][i][j]);
}
}
//1
dp[1][i][j] = Math.min(dp[1][i - 1][j], dp[1][i][j]);
if (h[i - 1] > h[i]) {
dp[1][i][j] = Math.min(dp[0][i - 1][j], dp[1][i][j]);
}
dp[1][i][j] = Math.min(dp[2][i - 1][j], dp[1][i][j]);
//2
dp[2][i][j] = Math.min(dp[0][i - 1][j] + dec(h[i], h[i - 1]), dp[2][i][j]);
}
}
// for(int i = 0; i < 3; i++){
// for(int j = 0; j <= n; j++){
// for(int k = 0; k <= m; k++){
// System.err.printf("dp[%d][%d][%d] = %d\n", i, j, k, dp[i][j][k]);
// }
// }
// }
for (int i = 1; i <= m; i++) {
int ans = inf;
for (int j = 0; j < 3; j++) {
ans = Math.min(ans, dp[j][n][i]);
}
out.append(ans).append(' ');
}
}
}
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(int c) {
cache.append(c);
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 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;
}
}
static class SequenceUtils {
public static void deepFill(Object array, int val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof int[]) {
int[] intArray = (int[]) array;
Arrays.fill(intArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFill(obj, val);
}
}
}
}
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | b32a83735d5a347546ce0bf8cb889861 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes |
import java.io.BufferedInputStream;
import java.util.Date;
import java.util.Scanner;
/**
* <a href='http://codeforces.com/problemset/problem/1012/C'>http://codeforces.com/problemset/problem/1012/C
* dp
* O(n ^ 2) TLE, don't know why
*/
public class Problem_1012C_Hills {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
while (in.hasNext()) {
int n = in.nextInt();
int[] a = new int[n + 2];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
if (n == 1) {
System.out.println(0);
continue;
}
if (n == 2) {
System.out.println(a[1] == a[2] ? 1 : 0);
continue;
}
// n >= 3
// dp1[i][j] means the minimum result to build j houses on first i hills with j-th house on i-th hill
// dp0[i][j] means the minimum result to build j houses on first i hills with j-th house not on i-th hill(on hills before)
// need not consider the height of hills on i + 1, i + 2, ... when you are acquiring dp[i] result
int[][] dp0 = new int[n + 1][(n + 1) / 2 + 1];
int[][] dp1 = new int[n + 1][(n + 1) / 2 + 1];
dp0[1][1] = 0;
dp1[2][1] = Math.max(0, 1 + a[1] - a[2]);
dp0[2][1] = Math.max(0, 1 + a[2] - a[1]);
dp1[3][2] = Math.max(0, 1 + a[2] - Math.min(a[1], a[3]));
for (int i = 3; i <= n; i++) {
dp1[i][1] = Math.max(0, 1 + a[i - 1] - a[i]);
dp0[i][1] = Math.min(
dp1[i - 1][1] + Math.max(0, a[i] - a[i - 1] + 1),
dp0[i - 1][1]);
}
for (int i = 3; i <= n; i++) {
int maxJ = (i + 1) / 2;
for (int j = 2; j <= (i + 1) / 2; j++) {
if (j == maxJ && j * 2 - 1 == i) {
// put house on hill 1, 3, 5, ..., i - 2, i
dp1[i][j] = dp1[i - 2][j - 1] +
Math.max(0, 1 + a[i - 1] - Math.min(a[i - 2], a[i]));
continue;
}
int x = Math.max(0, 1 + a[i - 1] - Math.min(a[i - 2], a[i]));
int y = Math.max(0, 1 + a[i - 1] - a[i]);
int z = Math.max(0, 1 + a[i] - a[i - 1]);
if (i == j * 2) {
dp0[i][j] = dp1[i - 1][j] + z;
} else {
dp0[i][j] = Math.min(dp0[i - 1][j], dp1[i - 1][j] + z);
}
dp1[i][j] = Math.min(dp1[i - 2][j - 1] + x, dp0[i - 2][j - 1] + y);
}
}
// get answer
boolean lineFirst = true;
for (int j = 1; j <= (n + 1) / 2; j++) {
if (lineFirst) {
lineFirst = false;
} else {
System.out.print(' ');
}
if (j * 2 - 1 == n) {
System.out.print(dp1[n][j]);
} else {
System.out.print(Math.min(dp0[n][j], dp1[n][j]));
}
}
System.out.println();
}
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | b09330a39fad78cb27566a943fc12795 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
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;
MyScan in = new MyScan(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int[][][] cache;
int ind = 0;
public void solve(int testNumber, MyScan in, PrintWriter out) {
int n = in.nextInt();
cache = new int[2][9][(n + 3) / 2];
int[] data = new int[n + 2];
for (int s = 0; s < n; s++) {
data[s + 1] = in.nextInt();
}
if (n == 1) {
out.println(0);
return;
}
int[][] next = new int[n + 2][3];
for (int s = 2; s < n; s++) {
next[s][0] = data[s];
next[s][1] = Math.min(data[s - 1] - 1, data[s]);
next[s][2] = Math.min(data[s + 1] - 1, data[s]);
Arrays.sort(next[s], 1, 3);
if (next[s][1] == next[s][2] || next[s][0] == next[s][2]) {
next[s] = Arrays.copyOf(next[s], 2);
}
if (next[s][1] == next[s][0]) {
next[s] = Arrays.copyOf(next[s], 1);
}
}
next[0] = new int[]{0};
next[n + 1] = new int[]{0};
next[1] = new int[]{data[1], Math.min(data[2] - 1, data[1])};
next[n] = new int[]{data[n], Math.min(data[n - 1] - 1, data[n])};
int[][] nn = nv();
nn[0][0] = 0;
nn[1][0] = data[1] - next[1][1];
for (int x = 0; x < n; x++) {
int[][] nn0 = nv();
for (int i1 = 0; i1 < next[x].length; i1++) {
int i = i1 * 3;
for (int i2 = 0; i2 < next[x + 1].length; i2++, i++) {
for (int moves = 0; moves < nn[i].length; moves++) {
if (nn[i][moves] == 1_000_000_000) continue;
int neIndex = i2 * 3;
for (int curIndex = 0; curIndex < next[x + 2].length; curIndex++, neIndex++) {
int tarMoves = moves;
if (next[x + 1][i2] > next[x][i1] && next[x + 1][i2] > next[x + 2][curIndex]) {
tarMoves++;
}
nn0[neIndex][tarMoves] = Math.min(nn0[neIndex][tarMoves], nn[i][moves] + next[x + 2][0] - next[x + 2][curIndex]);
}
}
}
}
nn = nn0;
// System.out.println(Arrays.toString(Matrix.rotate(nn)[(n - 1) / 2]));
// System.out.println(Arrays.toString(Matrix.rotate(nn)[(n + 1) / 2]));
}
long[] a = new long[nn[0].length];
Arrays.fill(a, Long.MAX_VALUE);
for (int[] aNn : nn) {
for (int l = 0; l < nn[0].length; l++) {
a[l] = Math.min(a[l], aNn[l]);
}
}
for (int s = nn[0].length - 1; s > 0; s--) {
a[s - 1] = Math.min(a[s - 1], a[s]);
}
for (int l = 1; l <= (n + 1) / 2; l++) {
out.print(a[l] + " ");
}
}
private int[][] nv() {
for (int[] l : cache[ind]) {
Arrays.fill(l, 1_000_000_000);
}
ind = 1 - ind;
return cache[1 - ind];
}
}
static class MyScan {
private final InputStream in;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0;
public int ptrbuf = 0;
public MyScan(InputStream in) {
this.in = in;
}
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 7577c600e24d70a27f79057f726887fb | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
public class C {
static int dp[][][];
static int N;
static int ar[];
static int low[];
static int dL[][];
static int dR[][];
static int INF = 1000000000;
public static void main(String[] args) {
JS in = new JS();
PrintWriter out = new PrintWriter(System.out);
N = in.nextInt();
int maxK = N/2;
if(N%2==1)maxK++;
ar = new int[N];
for(int i = 0; i < N; i++) ar[i] = in.nextInt();
low = new int[N];
low[0]=ar[0];
for(int i = 1; i < N; i++) low[i] = Math.min(ar[i], ar[i-1]-1);
dL = new int[2][N];
dR = new int[2][N];
for(int i = 0; i < N; i++) {
if(i > 0) {
dL[0][i] = Math.max(0, 1+ar[i-1]-ar[i]);
dL[1][i] = Math.max(0, 1+low[i-1]-ar[i]);
}
if(i < N-1) {
dR[0][i] = Math.max(0, 1+ar[i+1]-ar[i]);
dR[1][i] = dR[0][i];
}
}
dp = new int[2][maxK+1][N];
for(int a[][] : dp) {
for(int b[] : a) {
Arrays.fill(b, -1);
}
}
for(int i = 1; i <= maxK; i++) {
out.print(go(0,i,0)+" ");
}
out.println();
out.close();
}
static int go(int id, int left, int pL) {
if(left==0) return 0;
if(id >= N) return INF;
if(dp[pL][left][id] != -1) return dp[pL][left][id];
int res = INF;
//Make this a hill by raising it
//res = Math.min(res, Math.max(dL[pL][id], dR[pL][id]) + go(id+2, left-1, 0));
//Make this a hill by lowering 2 beside it
res = Math.min(res, dL[pL][id]+dR[pL][id] + go(id+2, left-1, 1));
//Skip this hill
res = Math.min(res, go(id+1, left, 0));
return dp[pL][left][id] = res;
}
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\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 2b6df60187e6837032128d97f4ea5fb8 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class c{
static long[] a;
static long[][][] dp;
static void solve(){
int n = ni()+2;
a = new long[n];
a[0]=-100000;
a[n-1]=-100000;
for(int i=1;i<=n-2;++i)a[i]=ni();
dp = new long[2][n+1][(n-1)/2 +1];
for(int i=0;i<=n;++i)for(int j=0;j<=(n-1)/2;++j)for(int k=0;k<2;++k)dp[k][i][j]=Integer.MAX_VALUE;
dp[0][0][0]=0;
for(int i=1;i<n-1;++i){
for(int j=0;j<=(i+1)/2;++j){
if(j==0)dp[0][i+1][j]=0L;
else{
if(i==1){
dp[1][i+1][j] = Math.max(0, -a[i]+1+ a[i+1]);
continue;
}
dp[0][i+1][j] = Math.min(Math.min(Math.min(dp[1][i-1][j], dp[0][i-1][j]), dp[0][i-2][j]), dp[1][i-2][j]);
dp[1][i+1][j] = Math.max(0, a[i+1]- a[i]+1) + Math.min(Math.min(dp[1][i-1][j-1]+ Math.max(0, -a[i]+1+Math.min(a[i-1], a[i-2]-1)), dp[0][i-1][j-1]+Math.max(0, -a[i]+1+ a[i-1])), Math.min(dp[0][i-2][j-1], dp[1][i-2][j-1]) + Math.max(0, -a[i]+1+ a[i-1]));
}
}
}
for(int i=1;i<=(n-1)/2;++i)out.print(Math.min(Math.min(dp[0][n-2][i], dp[1][n-2][i]), Math.min(dp[0][n-1][i], dp[1][n-1][i]))+" ");
out.println();
}
public static void main(String[] args){
solve();
out.flush();
}
private static InputStream in = System.in;
private static PrintWriter out = new PrintWriter(System.out);
private static final byte[] buffer = new byte[1<<15];
private static int ptr = 0;
private static int buflen = 0;
private static boolean hasNextByte(){
if(ptr<buflen)return true;
ptr = 0;
try{
buflen = in.read(buffer);
} catch (IOException e){
e.printStackTrace();
}
return buflen>0;
}
private static int readByte(){ if(hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isSpaceChar(int c){ return !(33<=c && c<=126);}
private static int skip(){int res; while((res=readByte())!=-1 && isSpaceChar(res)); return res;}
private static double nd(){ return Double.parseDouble(ns()); }
private static char nc(){ return (char)skip(); }
private static String ns(){
StringBuilder sb = new StringBuilder();
for(int b=skip();!isSpaceChar(b);b=readByte())sb.append((char)b);
return sb.toString();
}
private static int[] nia(int n){
int[] res = new int[n];
for(int i=0;i<n;++i)res[i]=ni();
return res;
}
private static long[] nla(int n){
long[] res = new long[n];
for(int i=0;i<n;++i)res[i]=nl();
return res;
}
private static int ni(){
int res=0,b;
boolean minus=false;
while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-'));
if(b=='-'){
minus=true;
b=readByte();
}
for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0');
return minus ? -res:res;
}
private static long nl(){
long res=0,b;
boolean minus=false;
while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-'));
if(b=='-'){
minus=true;
b=readByte();
}
for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0');
return minus ? -res:res;
}
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | cdb4863a30c2b298d01bf66d4d2f39f0 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//http://codeforces.com/problemset/problem/1012/C
public class Hills {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n + 1];
String[] astr = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(astr[i]);
}
//dp[house][k][i] = the best result to make k houses
//using squares 0 to i inclusive (with a house on square i iff house = 1).
//square i+1 is considered to have height a[i+1]. We can dig there, but we
//can't build on it.
int[][][] dp = new int[2][(n + 3) / 2][n];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= (n + 1) / 2; j++) {
if (j + k != 0) {
dp[k][j][i] = Integer.MAX_VALUE;
}
}
}
}
dp[1][1][0] = Math.max(0, 1 + a[1] - a[0]);
for (int i = 1; i < n; i++) {
for (int k = 1; k <= Math.min(n+1,(i + 3)) / 2; k++) {
// 1. do not build house here
dp[0][k][i] = Math.min(dp[0][k][i - 1], dp[1][k][i - 1]);
// 2. build house here
// a. Excavate the right and left sides to place house.
if (dp[0][k - 1][i - 1] != Integer.MAX_VALUE) {
dp[1][k][i] = dp[0][k - 1][i - 1] + Math.max(0, 1 + a[i + 1] - a[i]) + Math.max(0, 1 + a[i - 1] - a[i]);
}
// b. Though, if we placed a house 2 spaces ago, we may have already dug left side somewhat.
if (i > 1 && dp[1][k - 1][i - 2] != Integer.MAX_VALUE) {
dp[1][k][i] = Math.min(dp[1][k][i], dp[1][k - 1][i - 2] + Math.max(0, 1 + a[i + 1] - a[i]) +
Math.max(0, 1 + Math.min(a[i - 2] - 1, a[i - 1]) - a[i]));
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i < dp[0].length; i++) {
int best = Math.min(dp[0][i][n - 1], dp[1][i][n - 1]);
sb.append(best);
if (i != dp[0].length - 1) {
sb.append(" ");
}
}
System.out.println(sb);
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 954fb44432bfb44e5be2dcca868e8c7d | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
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;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EHills solver = new EHills();
solver.solve(1, in, out);
out.close();
}
static class EHills {
int[] arr;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
arr = new int[n + 5];
for (int i = 0; i < n; i++) arr[i] = in.scanInt();
int M = (n >> 1) + (n & 1);
int dpp[][][] = new int[3][M + 10][2];
for (int i = 0; i < 3; i++) {
for (int j = 0; j <= M; j++) {
dpp[i][j][0] = Integer.MAX_VALUE / 2;
dpp[i][j][1] = Integer.MAX_VALUE / 2;
}
}
dpp[0][0][0] = 0;
dpp[0][1][1] = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j <= M; j++) Arrays.fill(dpp[(i % 3)][j], Integer.MAX_VALUE / 2);
for (int j = 0; j <= M; j++) {
dpp[i % 3][j + 1][1] = Math.min(dpp[i % 3][j + 1][1], dpp[(i - 1) % 3][j][0] + P(i - 1, arr[i] - 1));
dpp[i % 3][j][0] = Math.min(dpp[i % 3][j][0], dpp[(i - 1) % 3][j][0]);
dpp[i % 3][j][0] = Math.min(dpp[i % 3][j][0], dpp[(i - 1) % 3][j][1] + P(i, arr[i - 1] - 1));
if (i - 2 >= 0)
dpp[i % 3][j + 1][1] = Math.min(dpp[i % 3][j + 1][1], dpp[(i - 2) % 3][j][1] + P(i - 1, Math.min(arr[i - 2], arr[i]) - 1));
}
}
for (int j = 1; j <= M; j++) {
out.print(Math.min(dpp[(n - 1) % 3][j][0], dpp[(n - 1) % 3][j][1]) + " ");
}
}
int P(int pos, int goal) {
if (arr[pos] <= goal) return 0;
return arr[pos] - goal;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 3fba5bfda9011ab0408b6f3de420937c | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import static java.lang.Math.min;
import static java.util.Arrays.fill;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt(), k = (n + 1) / 2 + 1;
int[] a = new int[n + 3];
for (int i = 0; i < n; i++)
a[i + 2] = in.nextInt();
long[][][] ans = new long[2][n + 3][k];
for (int i = 0; i < 2; i++)
for (int j = 0; j < n + 3; j++)
for (int l = 0; l < k; l++)
ans[i][j][l] = l == 0 ? 0 : Long.MAX_VALUE >> 2;
for (int i = 3; i < n + 3; i++) {
for (int j = 1; j < k; j++) {
ans[0][i][j] = (a[i] - min(a[i], a[i - 1] - 1)) + (a[i - 2] - min(a[i - 2], a[i - 1] - 1)) +
min(ans[0][i - 2][j - 1] -
(j > 1 ?
(min(a[i - 2], a[i - 1] - 1) <= min(a[i - 2], a[i - 3] - 1) ?
a[i - 2] - min(a[i - 2], a[i - 3] - 1) :
a[i - 2] - min(a[i - 2], a[i - 1] - 1))
: 0),
ans[1][i - 2][j - 1]);
ans[1][i][j] = min(ans[0][i - 1][j], ans[1][i - 1][j]);
}
}
for (int i = 1; i < k; i++)
out.print(min(ans[0][n + 2][i], ans[1][n + 2][i]) + " ");
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | d6447b5e4b2f943e9dac0b39b86c8034 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import static java.lang.Math.min;
import static java.util.Arrays.fill;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt(), k = (n + 1) / 2 + 1;
int[] a = new int[n + 3];
for (int i = 0; i < n; i++)
a[i + 2] = in.nextInt();
long[][][] ans = new long[2][n + 3][k];
for (int i = 0; i < 2; i++)
for (int j = 0; j < n + 3; j++)
for (int l = 0; l < k; l++)
ans[i][j][l] = l == 0 ? 0 : Long.MAX_VALUE >> 2;
for (int i = 3; i < n + 3; i++) {
for (int j = 1; j < k; j++) {
ans[0][i][j] = (a[i] - min(a[i], a[i - 1] - 1)) + (a[i - 2] - min(a[i - 2], a[i - 1] - 1))
+ min(ans[0][i - 2][j - 1] -
(j > 1 ? (min(a[i - 2], a[i - 1] - 1) <= min(a[i - 2], a[i - 3] - 1) ?
a[i - 2] - min(a[i - 2], a[i - 3] - 1) :
a[i - 2] - min(a[i - 2], a[i - 1] - 1)) : 0),
ans[1][i - 2][j - 1]);
ans[1][i][j] = min(ans[0][i - 1][j], ans[1][i - 1][j]);
}
}
long[] answer = new long[k - 1];
fill(answer, Long.MAX_VALUE);
for (int i = 0; i < 2; i++)
for (int j = 0; j < n + 3; j++)
for (int l = 1; l < k; l++)
answer[l - 1] = min(answer[l - 1], ans[i][j][l]);
for (int i = 0; i < k - 1; i++)
out.print(answer[i] + " ");
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | d49aa2d5ac779d1dcec6120fd8c3b250 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main2 {
public static class Gragh {
public ArrayList<Edge>[] edges;
public Gragh(int size) {
this.edges = new ArrayList[size];
for (int i = 0; i < size; ++i) {
edges[i] = new ArrayList<>();
}
}
public void add(int x, int y, int t) {
edges[x].add(new Edge(y, t));
}
public ArrayList<Edge> getn(int x) {
return edges[x];
}
}
public static class Edge {
int to;
int type;
public Edge(int ind, int t) {
this.to = ind;
this.type = t;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
int n = Integer.parseInt(reader.readLine());
int[] array = new int[n];
StringTokenizer st = new StringTokenizer(reader.readLine());
for(int i = 0; i < n; ++i){
array[i] = Integer.parseInt(st.nextToken());
}
if(n == 1){
System.out.println(0);
return;
}
int max = (n+1)/2;
long INF = 1000000000;
long[][] dp = new long[max][n];
for(int i = 0; i < max; ++i){
for(int j = 0; j < n; ++j){
dp[i][j] = INF;
}
}
long m = Integer.MAX_VALUE;
for(int i = 0; i < n; ++i){
if(i == 0){
dp[0][i] = Math.max(array[1] - array[0] + 1, 0);
}
else if(i == n-1){
dp[0][i] = Math.max(array[n-2] - array[n-1] + 1, 0);
}
else{
dp[0][i] = Math.max(array[i + 1] - array[i] + 1, 0) + Math.max(array[i-1] - array[i] + 1, 0);
}
m = Math.min(m, dp[0][i]);
}
writer.print(m + " ");
for(int i = 1; i < max; ++i){
long ans = Long.MAX_VALUE;
long min = Integer.MAX_VALUE;
for(int j = 0; j <= 2 * (i) - 2; ++j){
min = Math.min(dp[i-1][j], min);
}
for(int j = 2 * (i + 1) - 2; j < n; ++j){
dp[i][j] = min + dp[0][j];
long dop = dp[0][j] + dp[i-1][j-2];
dop -= Math.min(Math.max(array[j-1] - array[j] + 1, 0), Math.max(array[j-1]-array[j-2] + 1, 0));
dp[i][j] = Math.min(dop, dp[i][j]);
ans = Math.min(ans, dp[i][j]);
min = Math.min(min, dp[i-1][j-1]);
}
writer.print(ans + " ");
}
writer.close();
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 3ad9120fae0856f7229a24469f5a0463 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | //package round500;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int q = (n+1)/2+3;
long[][] dp = new long[3][q]; // 0:none(not candidate), 1:none(candidate), 2:decreased
long I = (long)1e17;
Arrays.fill(dp[0], (long)1e17);
Arrays.fill(dp[1], (long)1e17);
Arrays.fill(dp[2], (long)1e17);
dp[1][0] = 0;
for(int i = 1;i < n;i++){
long[][] ndp = new long[3][q];
Arrays.fill(ndp[0], (long)1e17);
Arrays.fill(ndp[1], (long)1e17);
Arrays.fill(ndp[2], (long)1e17);
for(int j = 0;j < q;j++){
if(dp[0][j] == I && dp[1][j] == I && dp[2][j] == I)continue;
// move a[i]
if(a[i-1] > a[i]){
if(j+1 < q)ndp[0][j+1] = Math.min(ndp[0][j+1], dp[1][j]);
ndp[0][j] = Math.min(ndp[0][j], dp[0][j]);
}
if(a[i-1] <= a[i]){
// down a[i]
if(j+1 < q)ndp[2][j+1] = Math.min(ndp[2][j+1], dp[1][j] + (a[i]-a[i-1]+1));
ndp[0][j] = Math.min(ndp[0][j], dp[0][j]);
ndp[0][j] = Math.min(ndp[0][j], dp[1][j]);
}
if(a[i-1] < a[i]){
ndp[1][j] = Math.min(ndp[1][j], dp[0][j]);
ndp[1][j] = Math.min(ndp[1][j], dp[1][j]);
}
// move a[i-1]
if(a[i-1] >= a[i]){
ndp[1][j] = Math.min(ndp[1][j], dp[1][j] + (a[i-1]-a[i]+1));
ndp[1][j] = Math.min(ndp[1][j], dp[0][j] + (a[i-1]-a[i]+1));
}
if(i-2 >= 0){
if(a[i-2]-1 < a[i]){
ndp[1][j] = Math.min(ndp[1][j], dp[2][j]);
}
if(a[i-2]-1 >= a[i]){
ndp[1][j] = Math.min(ndp[1][j], dp[2][j] + (a[i-2]-1-a[i]+1));
ndp[0][j] = Math.min(ndp[0][j], dp[2][j]);
}
}
}
dp = ndp;
}
long[] anss = new long[(n+1)/2+2];
Arrays.fill(anss, I);
for(int i = 0;i <= (n+1)/2;i++){
anss[i] = Math.min(anss[i], dp[0][i]);
anss[i+1] = Math.min(anss[i+1], dp[1][i]);
anss[i] = Math.min(anss[i], dp[2][i]);
}
for(int i = (n+1)/2;i >= 1;i--){
anss[i-1] = Math.min(anss[i], anss[i-1]);
}
for(int i = 1;i <= (n+1)/2;i++){
out.print(anss[i] + " ");
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 69cf033733cd1a13ace93754a8e1b170 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable{
public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();}
int n, oo = (int)2e9, a[], dp[][][][];
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
n = fs.nextInt();
a = fs.nextIntArray(n);
dp = new int[2][2][2][n/2+5];
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
for(int k = 0; k < 2; k++) {
Arrays.fill(dp[i][j][k], oo);
dp[i][j][k][0] = 0;
}
int x = 0;
for(int pos = n - 1; pos >= 0; pos--, x ^= 1) {
for(int canMakeLeft = 0; canMakeLeft < 2; canMakeLeft++) {
for(int prevHill = 0; prevHill < 2; prevHill++) {
if(prevHill == canMakeLeft && prevHill == 1) continue;
// if(prevHill == 1 && pos == 0) continue;
for(int numLeft = 0; numLeft < dp[x][canMakeLeft][prevHill].length; numLeft++) {
if(numLeft == 0) {
dp[x][canMakeLeft][prevHill][numLeft] = 0;
continue;
}
int nLeft = 0;
if(pos + 1 < n && a[pos] < a[pos+1]) nLeft = 1;
int mn = dp[x^1][nLeft][0][numLeft]; //<-- do nothing
if(canMakeLeft == 1) {
int cost = 0;
if(pos + 1 < n) {
cost += Math.max(0, a[pos+1] - a[pos] + 1);
}
//0, 1, numLeft-1
int next = dp[x^1][0][1][numLeft-1];
if(next != oo) {
next += cost;
mn = Math.min(mn, next);
}
}
int cost = 0;
if(pos + 1 < n) {
int use = a[pos];
if(prevHill == 1 && pos > 0) use = Math.min(use, a[pos-1]-1);
cost += Math.max(0, use - a[pos+1] + 1);
int next = dp[x^1][1][0][numLeft];//solve(1, 0, numLeft, pos+1);
if(next != oo) {
next += cost;
mn = Math.min(mn, next);
}
}
dp[x][canMakeLeft][prevHill][numLeft] = mn;
}
}
}
}
x ^= 1;
int[] res = new int[n / 2 + (n & 1)];
for(int i = res.length-1; i >= 0; i--) {
res[i] = Math.min(dp[x][1][0][i+1], dp[x][0][0][i+1]);
if(i + 1 < res.length)
res[i] = Math.min(res[i], res[i+1]);
}
for(int i = 0; i < res.length; i++)
out.print(res[i] + " ");
out.close();
}
// int solve(int canMakeLeft, int prevHill, int numLeft, int pos) {
//// System.out.printf("(%d, %d, %d)\n", canMakeLeft, numLeft, pos);
// if(numLeft < 0) return oo;
// if(pos == n) {
// if(numLeft > 0) return oo;
// return 0;
// }
// int ret = dp[canMakeLeft][prevHill][numLeft][pos];
// if(ret != -1) return ret;
//
// int nLeft = 0;
// if(pos + 1 < n && a[pos] < a[pos+1]) nLeft = 1;
// int res = solve(nLeft, 0, numLeft, pos + 1); //<-- do nothing
//
// //make pos a hill?
// if(canMakeLeft == 1) {
// int cost = 0;
// if(pos + 1 < n) {
// cost += Math.max(0, a[pos+1] - a[pos] + 1);
// }
// ret = solve(0, 1, numLeft-1, pos+1);
// if(ret != oo) {
// ret += cost;
// res = Math.min(res, ret);
// }
// }
//
// //set pos up to help the next index?
// int cost = 0;
// if(pos + 1 < n) {
// int use = a[pos];
// if(prevHill == 1) use = Math.min(use, a[pos-1]-1);
// cost += Math.max(0, use - a[pos+1] + 1);
// ret = solve(1, 0, numLeft, pos+1);
// if(ret != oo) {
// ret += cost;
// res = Math.min(res, ret);
// }
// }
//
// return dp[canMakeLeft][prevHill][numLeft][pos] = res;
// }
// void fill() {
// for(int[][] d : dp)
// for(int[] dd : d)
// Arrays.fill(dd, -1);
// for(int[][][] d : dp)
// for(int[][] dd : d)
// for(int[] ddd : dd)
// Arrays.fill(ddd, -1);
// }
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) 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() {
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 | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output | |
PASSED | 8e76590828ad6c9c5d8bf66a376b21a1 | train_000.jsonl | 1532938500 | Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5,β4,β6,β2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up. | 512 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
private static final long INF = 1234567890987654321L;
public static void solve(FastIO io) {
int N = io.nextInt();
int K = (N + 1) >> 1;
long[] A = new long[N + 2];
for (int i = 1; i <= N; ++i) {
A[i] = io.nextLong();
}
A[0] = A[N + 1] = -INF;
long[] dp = new long[N + 2];
for (int i = 1; i <= K; ++i) {
long[] next = new long[N + 2];
Arrays.fill(next, INF);
long prevBestNoExcav = INF;
if (i == 1) {
prevBestNoExcav = 0;
}
long bestAns = INF;
for (int j = 1; j <= N; ++j) {
// construct house with j-3 or before, assuming j-1 is not yet excavated
if (j >= 3) {
prevBestNoExcav = Math.min(prevBestNoExcav, dp[j - 3]);
}
next[j] = Math.min(next[j], prevBestNoExcav + getTrim(A[j], A[j - 1]) + getTrim(A[j], A[j + 1]));
// construct house with j-2, assuming j-1 is excavated already
if (i > 1 && j >= 3) {
long prev = Math.min(A[j - 2] - 1, A[j - 1]);
next[j] = Math.min(next[j], dp[j - 2] + getTrim(A[j], prev) + getTrim(A[j], A[j + 1]));
}
bestAns = Math.min(bestAns, next[j]);
}
io.printf(bestAns + " ");
dp = next;
}
io.println();
}
private static long getTrim(long ht, long neighbor) {
if (neighbor < ht) {
return 0;
}
return neighbor - (ht - 1);
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
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 printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["5\n1 1 1 1 1", "3\n1 2 3", "5\n1 2 3 2 2"] | 1 second | ["1 2 2", "0 2", "0 1 3"] | NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1,β0,β1,β1,β1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1,β0,β1,β0,β1, and hills 1,β3,β5 become suitable for construction. | Java 8 | standard input | [
"dp"
] | 9534b468bfb6126fc16b896532ced8c5 | The first line of input contains the only integer n (1ββ€βnββ€β5000)βthe number of the hills in the sequence. Second line contains n integers ai (1ββ€βaiββ€β100β000)βthe heights of the hills in the sequence. | 1,900 | Print exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.