exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 5ab31cfb91d1a8e38e2765611d78ce58 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.*;
public class NewRoute
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
int n=ob.nextInt();
Long a[]=new Long[n];
for(int i=0;i<n;i++)
a[i]=ob.nextLong();
Arrays.sort(a);
int s=0;
long min=Integer.MAX_VALUE;
for(int i=0;i<n-1;i++)
{
if(Math.abs(a[i]-a[i+1])==min)
s++;
if(Math.abs(a[i]-a[i+1])<min)
{
min=Math.abs(a[i]-a[i+1]);
s=1;
}
}
System.out.println(min+" "+s);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | f0d6a13f300821edb2a7ebb2eabcf0fa | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | //package TIM;
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
public class NewRoute {
static Scanner input = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String args[]) {
int n = input.nextInt();
Long a[] = new Long[n];
for (int i = 0; i < n; i++)
a[i] = input.nextLong();
Arrays.sort(a);
int num = 0;
long min = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
long t = a[i] - a[i - 1];
if (t == min)
num++;
if (t < min) {
min = t;
num = 1;
}
}
System.out.println(min + " " + num);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | fad9b1316d167d8e0250c04e1329cc11 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.*;
public class NewRoute
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
int n=ob.nextInt();
Long a[]=new Long[n];
for(int i=0;i<n;i++)
a[i]=ob.nextLong();
java.util.Arrays.sort(a);
int s=0;
long min=Integer.MAX_VALUE;
for(int i=0;i<n-1;i++)
{
if(Math.abs(a[i]-a[i+1])==min)
s++;
if(Math.abs(a[i]-a[i+1])<min)
{
min=Math.abs(a[i]-a[i+1]);
s=1;
}
}
System.out.println(min+" "+s);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | c04880de7cb3faedd5b14fab0064ebc0 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.*;
import java.util.*;
public class NewRoute {
static Scanner input = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String args[]) {
int n = input.nextInt();
Long a[] = new Long[n];
for (int i = 0; i < n; i++)
a[i] = input.nextLong();
Arrays.sort(a);
int num = 0;
long min = Integer.MAX_VALUE;
for (int i = 0; i < n - 1; i++) {
if (Math.abs(a[i] - a[i + 1]) == min)
num++;
if (Math.abs(a[i] - a[i + 1]) < min) {
min = Math.abs(a[i] - a[i + 1]);
num = 1;
}
}
System.out.println(min + " " + num);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 39ef8c3b274a1d66fefe2ac0940f2481 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | //package TIM;
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
int n = input.nextInt();
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = input.nextLong();
Arrays.sort(a);
int num = 0;
long min = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
long t = a[i] - a[i - 1];
if (t == min)
num++;
if (t < min) {
min = t;
num = 1;
}
}
System.out.println(min + " " + num);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 768d6315a48ca240233b618deba60109 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
int min = Integer.MAX_VALUE;
for (int i = 1; i < n; i++)
min = Math.min(min, Math.abs(a[i] - a[i - 1]));
int res = 0;
for (int i = 1; i < n; i++)
if (Math.abs(a[i] - a[i - 1]) == min)
res++;
System.out.println(min + " " + res);
sc.close();
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 60d5800d4bc15eb332a2ecdc0af9a136 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 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 A{
public static void main(String[] args) {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = scan.nextInt();
Arrays.sort(a);
int min = 2*(int)1e9;
for(int i = 1; i < n; i++)min = Math.min(min, a[i]-a[i-1]);
int c = 0;
for(int i = 1; i < n; i++)if(a[i]-a[i-1] == min) c++;
out.println(min+" "+c);
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 | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 23c9e0a4d958b9175b5c88b99e42affb | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static void sort(int arr[]){
int cnt[]=new int[(1<<16)+1];
int ys[]=new int[arr.length];
for(int j=0;j<=16;j+=16){
Arrays.fill(cnt,0);
for(int x:arr){cnt[(x>>j&0xFFFF)+1]++;}
for(int i=1;i<cnt.length;i++){cnt[i]+=cnt[i-1];}
for(int x:arr){ys[cnt[x>>j&0xFFFF]++]=x;}
{ final int t[]=arr;arr=ys;ys=t;}
}
if(arr[0]<0||arr[arr.length-1]>=0)return;
int i,j,c;
for(i=arr.length-1,c=0;arr[i]<0;i--,c++){ys[c]=arr[i];}
for(j=arr.length-1;i>=0;i--,j--){arr[j]=arr[i];}
for(i=c-1;i>=0;i--){arr[i]=ys[c-1-i];}
}
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=sc.nextIntArray(n);
sort(a);
int min=(int)2e9;
int cnt=0;
for(int i=1;i<n;i++)
{
int sub=Math.abs(a[i]-a[i-1]);
if(sub==min)
{
cnt++;
}
else if(sub<min)
{
min=sub;
cnt=1;
}
}
out.println(min+" "+cnt);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
private FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
private String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
private int nextInt() {return Integer.parseInt(next());}
private long nextLong() {return Long.parseLong(next());}
private double nextDouble() {return Double.parseDouble(next());}
private 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;
}
private int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
private 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 | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 92d4cd9cc122b26a5ed2ff6efd98ebcf | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.PriorityQueue;
import java.util.Scanner;
public final class CodeForces792A {
public static void main(final String... args) throws Exception {
exec(new BufferedReader(new InputStreamReader(System.in)), System.out);
}
static void exec(final BufferedReader in, final PrintStream out) throws IOException {
final Scanner scanner = new Scanner(in);
final int numCities = scanner.nextInt();
final PriorityQueue<Integer> cityCoordinates = new PriorityQueue<Integer>();
for (int i = 0; i < numCities; i++) {
cityCoordinates.add(scanner.nextInt());
}
int minDistance = Integer.MAX_VALUE;
int minCount = 0;
int previous = cityCoordinates.remove();
for (int i = 1; i < numCities; i++) {
final int current = cityCoordinates.remove();
final int distance = Math.abs(current - previous);
if (distance < minDistance) {
minDistance = distance;
minCount = 1;
}
else if (distance == minDistance) {
minCount++;
}
previous = current;
}
out.println(minDistance + " " + minCount);
}
}
| Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | e509554af9e8bb23330872609926dfbf | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 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 A{
// test
public static void main(String[] args) {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = scan.nextInt();
Arrays.sort(a);
int min = 2*(int)1e9;
for(int i = 1; i < n; i++)min = Math.min(min, a[i]-a[i-1]);
int c = 0;
for(int i = 1; i < n; i++)if(a[i]-a[i-1] == min) c++;
out.println(min+" "+c);
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 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;
}
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 4a6f2bd9b58ad5b32e7938f615d4d8f7 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class A {
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
ArrayList<Integer> arr = new ArrayList<Integer>(n);
for(int i = 0; i < n; ++i) arr.add(in.nextInt());
Collections.sort(arr);
int min = arr.get(1) - arr.get(0), count = 1;
for(int i = 2; i < n; ++i) {
int diff = Math.abs(arr.get(i) - arr.get(i - 1));
if(diff == min) count++;
else if(diff < min) { min = diff; count = 1; }
}
out.println(min + " " + count);
out.flush();
out.close();
}
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];int cnt=0,c;while((c=read())!=-1){if(c==10)break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt - 1);
}public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
}public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
}public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;
}private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;
}private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];
}public void close() throws IOException{if(din==null) return;din.close();}
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 19f68fd709d90cfb94c45e4fa254025b | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
ArrayList<Integer> arr = new ArrayList<Integer>(n);
for(int i = 0; i < n; ++i) arr.add(sc.nextInt());
Collections.sort(arr);
int min = arr.get(1) - arr.get(0), count = 1;
for(int i = 2; i < n; ++i) {
int diff = arr.get(i) - arr.get(i - 1);
if(diff == min) count++;
else if(diff < min) { min = diff; count = 1; }
}
out.println(min + " " + count);
out.flush();
out.close();
}
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 9e766e0a3dde03d99e67075028ae38e3 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class ECR18Div2A {
public static void main(String[] args) {
FastScanner in=new FastScanner();
int n=in.nextInt();
TreeMap<Integer,Integer> a=new TreeMap<Integer,Integer>();
for(int i=0;i<n;i++){
int aa=in.nextInt();
a.put(aa,a.containsKey(aa)?a.get(aa)+1:1);
}
int[][] b=new int[n][2];
int p=0;
for(int aa:a.keySet()){
b[p][0]=aa;
b[p][1]=a.get(aa);
p++;
}
int min=Integer.MAX_VALUE;
int cnt=0;
for(int i=0;i<p-1;i++){
int bb=Math.abs(b[i][0]-b[i+1][0]);
if(min>bb){
cnt=Math.min(b[i][1],b[i+1][1]);
min=bb;
}else if(min==bb){
cnt+=Math.min(b[i][1],b[i+1][1]);
}
}
System.out.println(min+" "+cnt);
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));}
String nextToken(){
while(st==null||!st.hasMoreElements())
try{st=new StringTokenizer(br.readLine());}catch(Exception e){}
return st.nextToken();
}
int nextInt(){return Integer.parseInt(nextToken());}
long nextLong(){return Long.parseLong(nextToken());}
double nextDouble(){return Double.parseDouble(nextToken());}
}
}
| Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 2d8d45016bf65dce882626d3b64f8024 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.Scanner;
public class CodeForce11
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Long a[]=new Long[n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
java.util.Arrays.sort(a);
int count=0;
long min=Integer.MAX_VALUE;
for(int i=0;i<n-1;i++)
{
if(Math.abs(a[i]-a[i+1])==min)
count++;
if(Math.abs(a[i]-a[i+1])<min)
{
min=Math.abs(a[i]-a[i+1]);
count=1;
}
}
System.out.println(min+" "+count);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 92bc7e11e72c57e354e6d779f12b7078 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.Scanner;
public class CodeForce11
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Long a[]=new Long[n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
java.util.Arrays.sort(a);
int count=0;
long min=Integer.MAX_VALUE;
for(int i=0;i<n-1;i++)
{
if(Math.abs(a[i]-a[i+1])==min)
count++;
if(Math.abs(a[i]-a[i+1])<min)
{
min=Math.abs(a[i]-a[i+1]);
count=1;
}
}
System.out.println(min+" "+count);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | fda367a01a7c7e235f8fda23e1b5698b | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
new Main().solve();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.0000000001;
PrintWriter out;
int n;
int m;
ArrayList<Integer>[] g = new ArrayList[200000];
void solve() throws IOException {
Reader in;
BufferedReader br;
try {
//br = new BufferedReader( new FileReader("input.txt") );
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Random rnd = new Random();
for (int i = 0; i < n; i++) {
int k1 = rnd.nextInt(n);
int k2 = rnd.nextInt(n);
int t = a[k1];
a[k1] = a[k2];
a[k2] = t;
}
Arrays.sort(a);
int cnt = 0;
int min = inf;
for (int i = 0; i < n-1; i++) {
if (a[i+1] - a[i] == min) {
cnt++;
}
if (a[i+1] - a[i] < min) {
cnt = 1;
min = a[i+1] - a[i];
}
}
out.print(min+" ");
out.print(cnt);
out.flush();
out.close();
}
class Pair implements Comparable<Pair>{
long a;
long b;
Pair(long a, long b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a > p.a) return 1;
if (a < p.a) return -1;
return 0;
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 06df6ad4ede31bf7ef816af878a6b10a | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.KeyStore.Entry;
import java.util.*;
public class TestClass {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
public static void Merge(int a[],int p,int r){
if(p<r){
int q = (p+r)/2;
Merge(a,p,q);
Merge(a,q+1,r);
Merge_Array(a,p,q,r);
}
}
public static void Merge_Array(int a[],int p,int q,int r){
int b[] = new int[q-p+1];
int c[] = new int[r-q];
for(int i=0;i<b.length;i++)
b[i] = a[p+i];
for(int i=0;i<c.length;i++)
c[i] = a[q+i+1];
int i = 0,j = 0;
for(int k=p;k<=r;k++){
if(i==b.length){
a[k] = c[j];
j++;
}
else if(j==c.length){
a[k] = b[i];
i++;
}
else if(b[i]<c[j]){
a[k] = b[i];
i++;
}
else{
a[k] = c[j];
j++;
}
}
}
private static void soln() {
int n = nI();
int arr[] = new int[n];
for(int i=0;i<n;i++)
arr[i] = nI();
Merge(arr,0,n-1);
int min = Integer.MAX_VALUE;
for(int i=1;i<n;i++){
if(arr[i]-arr[i-1]<min)
min = arr[i]-arr[i-1];
}
long ans = 0;
for(int i=1;i<n;i++)
if(arr[i]-arr[i-1]==min)
ans++;
if(min==0)
ans = (ans*(ans+1))/2;
pw.println(min+" "+ans);
}
public static void main(String[] args) {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int nI() {
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;
}
private static long nL() {
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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nLi() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 5ddc43e2353b059f35357b53a92381f4 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;
public class A {
public static void main(String[] args) {
// Scanner scan = new Scanner(System.in);
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = new int[n];
for(int i=0; i<n; ++i) {
a[i] = in.nextInt();
}
Random random = new Random();
for(int i = n-1; i >= 1; --i) {
int x = random.nextInt(n);
int temp = a[x];
a[x] = a[i];
a[i] = temp;
}
Arrays.sort(a);
int min = Integer.MAX_VALUE;
int cnt = 0;
for(int i=0; i<n-1; ++i) {
int diff = Math.abs(a[i] - a[i+1]);
if(diff < min) {
min = diff;
cnt = 1;
} else if(diff == min) {
cnt++;
}
}
System.out.println(min + " " + cnt);
out.close();
// scan.close();
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | bed6292d04d3b2d76da1c077f711ebcb | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;
public class A {
public static void main(String[] args) {
// Scanner scan = new Scanner(System.in);
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = new int[n];
for(int i=0; i<n; ++i) {
a[i] = in.nextInt();
}
Random random = new Random();
for(int i = n-1; i >= 1; --i) {
int x = random.nextInt(i);
int temp = a[x];
a[x] = a[i];
a[i] = temp;
}
Arrays.sort(a);
int min = Integer.MAX_VALUE;
int cnt = 0;
for(int i=0; i<n-1; ++i) {
int diff = Math.abs(a[i] - a[i+1]);
if(diff < min) {
min = diff;
cnt = 1;
} else if(diff == min) {
cnt++;
}
}
System.out.println(min + " " + cnt);
out.close();
// scan.close();
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | f226faf7982609ffb9877a114e4e6f6c | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.io.*;
import java.util.*;
public class A1008 {
public static void main(String [] args) /*throws Exception*/ {
InputStream inputReader = System.in;
OutputStream outputReader = System.out;
InputReader in = new InputReader(inputReader);//new InputReader(new FileInputStream(new File("input.txt")));new InputReader(inputReader);
PrintWriter out = new PrintWriter(outputReader);//new PrintWriter(new FileOutputStream(new File("output.txt")));
Algorithm solver = new Algorithm();
solver.solve(in, out);
out.close();
}
}
class Algorithm {
void solve(InputReader ir, PrintWriter pw) {
int n = ir.nextInt(), min1 = Integer.MAX_VALUE, min2 = 0;
int [] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ir.nextInt();
Random random = new Random();
for(int i = n-1; i >= 1; --i) {
int x = random.nextInt(i);
int temp = a[x];
a[x] = a[i];
a[i] = temp;
}
Arrays.sort(a);
for (int i = 0, diff; i < n - 1; i++) {
diff = Math.abs(a[i] - a[i + 1]);
if (diff < min1) {
min1 = diff;
min2 = 1;
} else if (diff == min1) min2++;
}
System.out.println(min1 + " " + min2);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 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();
}
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;
}
String [] toArray() {
return nextLine().split(" ");
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 97e5b47f05e856f8485df243b6ba5426 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | //package com.rengu.AlgorithmTest;
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
FastScanner in;
PrintWriter out;
public void run() {
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.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public void solve() {
int t;
t = in.nextInt();
// Integer dis[] = new Integer[t];
Integer dis[]=new Integer[t];
for (int i = 0; i < t; i++) {
dis[i] = in.nextInt();
}
Arrays.sort(dis);
int MIN = Integer.MAX_VALUE, distance = 0;
for (int i = 0; i < dis.length - 1; i++) {
distance = dis[i + 1] - dis[i];
MIN = Math.min(MIN, distance);
}
int count = 0;
for (int i = 0; i < dis.length - 1; i++) {
if (dis[i + 1] - dis[i] == MIN) {
count += 1;
}
}
System.out.println(MIN+" "+count);
}
public static void main(String[] args) {
new Main().run();
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | f5ab5da5c3bfea3d141a545cfa9fdbe0 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n =in.nextInt();
Long[] vs = new Long[n];
for(int i=0;i<n;i++) {
vs[i] = in.nextLong();
}
Arrays.sort(vs);
long minAns = Long.MAX_VALUE;
int cnt = 0;
for(int i=1;i<n;i++) {
long d = Math.abs(vs[i]-vs[i-1]);
if(d < minAns) {
minAns = d;
cnt = 1;
} else if(d == minAns) {
cnt++;
}
}
System.out.println(minAns + " " + cnt);
}
} | Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 7169fb6685a602caa08079d461a95460 | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | //package com.rengu.AlgorithmTest;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
Long arr[] = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextLong();
}
Arrays.sort(arr);
long dis = 0;
int sum = 0;
long MIN = Long.MAX_VALUE;
for (int i = 0; i < arr.length - 1; i++) {
// dis = arr[i + 1] - arr[i];
dis = Math.abs(arr[i + 1] - arr[i]);
if (dis < MIN) {
MIN = dis;
sum = 1;
} else if (dis == MIN) {
sum += 1;
}
}
System.out.println(MIN + " " + sum);
}
}
| Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | 8db8569b27b25daf91a29926dcd2097d | train_002.jsonl | 1490625300 | There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. | 256 megabytes | //package com.rengu.AlgorithmTest;
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.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
FastScanner in;
PrintWriter out;
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public void run() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
public void solve() {
int n = in.nextInt();
Long arr[] = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextLong();
}
Arrays.sort(arr);
long MIN = Long.MAX_VALUE;
long sum = 0;
long dis = 0;
for (int i = 0; i < arr.length - 1; i++) {
dis = arr[i + 1] - arr[i];
if (dis < MIN) {
MIN = dis;
sum = 1;
} else if (dis == MIN) {
sum += 1;
}
}
/*
* int sum = 0; for (int i = 0; i < arr.length - 1; i++) { if (arr[i +
* 1] - arr[i] == MIN) { sum += 1; } }
*/
System.out.println(MIN + " " + sum);
}
public static void main(String[] args) {
new Main().run();
}
}
| Java | ["4\n6 -3 0 4", "3\n-2 0 2"] | 1 second | ["2 1", "2 2"] | NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. | Java 8 | standard input | [
"implementation",
"sortings"
] | 5f89678ae1deb1d9eaafaab55a64197f | The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. | 1,100 | Print two integer numbers — the minimal distance and the quantity of pairs with this distance. | standard output | |
PASSED | c81600304e94f294ead11df447648f3d | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.TreeMap;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Bat-Orgil
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();
int[] x= new int[n];
int[] y= new int[n];
long ans= 1L*n*(n-1)*(n-2)/6;
for(int i=0; i<n; i++){
x[i]=in.nextInt();
y[i]=in.nextInt();
}
long minus=0;
for(int i=0; i<n; i++){
TreeMap<Double, Integer> map= new TreeMap();
for(int j=i+1; j<n; j++){
double c;
if( x[j] == x[i]){
c=10000.00;
}else {
c = (double) (y[j] - y[i]) / (double) (x[j] - x[i]);
}
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else if(map.higherKey(c) != null && Math.abs((map.higherKey(c)- c)) < 0.000001) {
map.put(map.higherKey(c), map.get(map.higherKey(c))+1);
}else if(map.lowerKey(c) != null && Math.abs((map.lowerKey(c) - c)) < 0.000001){
map.put(map.lowerKey(c), map.get(map.lowerKey(c))+1);
}else{
map.put(c, 1);
}
}
for(Double key : map.keySet()){
if(map.get(key) >=2){
int c= map.get(key);
minus+= 1L*c*(c-1)/2;
}
}
}
out.println(ans-minus);
}
}
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());
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 997adde898ec11e5b5531367f4afdb4d | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import javax.print.attribute.IntegerSyntax;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void solve1() {
int n = IO.readInt();
int[] x = new int[n];
int[] y = new int[n];
for (int index = 0; index < n; ++index) {
x[index] = IO.readInt();
y[index] = IO.readInt();
}
long m = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
int a = (x[k] - x[i]) * (y[j] - y[i]);
int b = (y[k] - y[i]) * (x[j] - x[i]);
if (a == b) {
m++;
}
}
}
}
long all = n * (n - 1) * (n - 2) / 6;
IO.println(all - m);
}
public static void solve() {
int n = IO.readInt();
int[] x = new int[n];
int[] y = new int[n];
TreeMap<Line, Integer> map = new TreeMap<>();
for (int i = 0; i < n; ++i) {
x[i] = IO.readInt();
y[i] = IO.readInt();
for (int j = 0; j < i; ++j) {
double k = x[i] != x[j] ? ((double) y[i] - y[j]) / (x[i] - x[j]) : Double.POSITIVE_INFINITY;
double b = x[i] != x[j] ? (y[j] - x[j] * k) : x[i];
Line line = new Line(k, b);
Integer c = map.get(line);
if (c == null) {
c = 0;
}
map.put(line, c + 1);
}
}
long m = 0;
for (int v : map.values()) {
if (v > 1) {
m += v * ((long) java.lang.Math.sqrt(2 * v) - 1) / 3;
}
}
long all = ((long) n) * (n - 1) * (n - 2) / 6;
IO.println(all - m);
}
private static class Line implements Comparable<Line> {
double k;
double b;
public Line(double k, double b) {
this.k = k;
this.b = b;
}
@Override
public int compareTo(Line o) {
if (java.lang.Math.abs(k - o.k) > 0.000001f) {
return Double.compare(k, o.k);
}
return java.lang.Math.abs(b - o.b) > 0.000001f ? Double.compare(b, o.b) : 0;
}
}
// Input/Output ================================
public static class IO {
private static Scanner scanner;
private static PrintWriter writer;
public static void setUp(InputStream in, OutputStream out) {
scanner = new Scanner(new java.io.BufferedInputStream(in));
writer = new PrintWriter(out);
}
public static boolean isEmpty() {
return !scanner.hasNext();
}
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
public static String readLine() {
String line;
try {
line = scanner.nextLine();
} catch (Exception e) {
line = null;
}
return line;
}
public static String readString() {
return scanner.next();
}
public static int readInt() {
return scanner.nextInt();
}
public static double readDouble() {
return scanner.nextDouble();
}
public static float readFloat() {
return scanner.nextFloat();
}
public static long readLong() {
return scanner.nextLong();
}
public static char readChar() {
return scanner.findInLine("[^\\s]").charAt(0);
}
public static void print(Object o) {
writer.print(o);
writer.flush();
}
public static void println(Object o) {
writer.println(o);
writer.flush();
}
}
// Algorithms ================================
private static class Algo {
private static int binSearch(int[] array, int n, int lo, int hi) {
if (lo > hi) {
return lo;
}
int mid = lo + (hi - lo) / 2;
int cmp = (int) java.lang.Math.signum(n - array[mid]);
if (cmp < 0) {
return binSearch(array, n, lo, mid - 1);
} else if (cmp == 0) {
return mid;
} else {
return binSearch(array, n, mid + 1, hi);
}
}
private static void permutations(int n) {
int[] p = new int[n];
for (int index = 0; index < n; ++index) {
p[index] = index + 1;
}
while (true) {
IO.println(Arrays.toString(p));
int k = n - 1;
while (k > 0) {
if (p[k] < p[k - 1]) {
k--;
}
else {
break;
}
}
if (k == 0) {
break;
}
int j = n - 1;
while (p[j] < p[k - 1]) {
j--;
}
int t = p[j];
p[j] = p[k - 1];
p[k - 1] = t;
int i = 0;
while (k + i < n - 1 - i) {
t = p[k + i];
p[k + i] = p[n - i - 1];
p[n - i - 1] = t;
i++;
}
}
}
private static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
if (number <= 3) {
return true;
}
if (number % 2 == 0 || number % 3 == 0) {
return false;
}
int i = 5;
while (i * i <= number) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
i += 6;
}
return true;
}
private static boolean isPalindrome(int number) {
int n = number;
int reverse = 0;
while (n > 0) {
reverse *= 10;
reverse += (n % 10);
n /= 10;
}
return reverse == number;
}
public static int gcd(int a,int b) {
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
}
private static class Math {
static long c(int n, int k) {
if (n == 0 && k == 0) {
return 1;
}
int d = 1000;
int l = 1000000007;
long[][] c = new long[d + 1][d + 1];
for (int i = 1; i <= d; ++i) {
for (int j = 0; j <= i; ++j) {
if (i == j || j == 0) {
c[i][j] = 1;
}
else {
c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % l;
}
}
}
return c[n][k];
}
}
public static void main(String[] args) {
IO.setUp(System.in, System.out);
/*
try {
IO.setUp(new FileInputStream("encode.in"), new FileOutputStream("encode.out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
*/
solve();
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 1b052f5de89af0e6585a4458dfc0072c | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | //
// Vanya.java
// Created by Alister Estrada Cueto on 9/26/18.
import java.util.*;
public class Vanya{
public static void main(String[] args){
int[] x = new int[2505];
int[] y = new int[2505];
int[] a = new int[4100005];
Map<Long, Integer> hashmap = new HashMap<Long, Integer>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 2; i <= 2000; i++){
a[i*i-i] = i;
}
sc.nextLine();
for (int i = 0; i < n; i++){
String num = sc.nextLine();
x[i] = Integer.parseInt(num.split(" ")[0]);
y[i] = Integer.parseInt(num.split(" ")[1]);
}
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (i != j){
int kc = y[j] - y[i];
int kz = x[j] - x[i];
int bc = y[i]*(x[j] - x[i]) - x[i]*(y[j]-y[i]);
int bz = x[j] - x[i];
if (kz != 0){
int tmp = gcd(Math.abs(kc), Math.abs(kz));
kc /= tmp; kz /= tmp;
if (kc < 0){
kc = -kc; kz = -kz;
}
if (kc == 0) kz = 1;
tmp = gcd(Math.abs(bc), Math.abs(bz));
bc /= tmp; bz /= tmp;
if (bc < 0){
bc = -bc; bz = -bz;
}
if (bc == 0) bz = 1;
}
else{
kc = bc = x[i];
}
long hsh = (long)bc*270000*100000 + (long)bz*9000000 + (long)kc*300 + (long)kz;
int k = 0;
if (hashmap.containsKey(hsh)){
k = hashmap.get(hsh);
}
hashmap.put(hsh, k+2);
}
}
}
long ans = ((long)n*(n-1)*(n-2))/6;
Iterator <Long> itr = hashmap.keySet().iterator();
while (itr.hasNext()){
int tmp = hashmap.get(itr.next());
tmp = a[tmp/2];
ans -= ((long)tmp*(tmp-1)*(tmp-2))/6;
}
System.out.println(ans);
}
static int gcd(int a, int b){
if (b == 0) return a;
return gcd(b,a%b);
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | b101660159d98e02a49938b7577238d7 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes |
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class D {
public static void main(String cd[])
{
FasterScanner in=new FasterScanner();
int n=in.nextInt();
int x[]=new int[n];
int y[]=new int[n];
for(int i=0;i<n;i++){
x[i]=in.nextInt();
y[i]=in.nextInt();
}
long count=0;
for(int i=0;i<n-2;i++){
for(int j=i+1;j<n-1;j++){
double dx1=(double)(x[i]-x[j]);
double dy1=(double)(y[i]-y[j]);
for(int k=j+1;k<n;k++){
double dx2=(double)(x[j]-x[k]);
double dy2=(double)(y[j]-y[k]);
if(dx1*dy2!=dx2*dy1){
count++;
}
}
}
}
System.out.println(count);
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.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) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 33fa04f047977bb792ebde11fd0cc930 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.Scanner;
public class P1 {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double[] x = new double[n];
double[] y = new double[n];
double x1 = 0;
double y1 = 0;
double x2 = 0;
double y2 = 0;
double x3 = 0;
double y3 = 0;
for(int i=0; i<n; i++){
x[i] = in.nextDouble();
y[i] = in.nextDouble();
}
int check = 0;
if(n>2){
for(int i=0; i<x.length; i++){
x1 = x[i];
y1 = y[i];
for(int j = i+1; j<x.length; j++){
x2 = x[j];
y2 = y[j];
for(int k = j+1; k<x.length; k++){
x3 = x[k];
y3 = y[k];
if((y3-y1)*(x2-x1) != (y2-y1)*(x3-x1)){
check++;
}
}
}
}
System.out.println(check);
}
else{
System.out.println(0);
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 77c14919c0b78078f4fd7255590e13e6 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.*;
public class CF {
FastScanner in;
PrintWriter out;
class Point implements Comparable<Point> {
int x, y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
return Integer.signum(x * o.y - o.x * y);
}
}
void solve() {
int n = in.nextInt();
Point[] a = new Point[n];
Point[] b = new Point[n - 1];
for (int i = 0; i < n; i++) {
a[i] = new Point(in.nextInt(), in.nextInt());
}
for (int i = 0; i < b.length; i++) {
b[i] = new Point(0, 0);
}
long result = n * 1L * (n - 1) * 1L * (n - 2) / 6;
long sub = 0;
for (int i = 0; i < n; i++) {
int cnt = n - i - 1;
for (int j = i + 1; j < n; j++) {
b[j - i - 1].x = a[j].x - a[i].x;
b[j - i - 1].y = a[j].y - a[i].y;
}
for (int j = 0; j < cnt; j++) {
if (b[j].y < 0 || b[j].y == 0 && b[j].x < 0) {
b[j].y *= -1;
b[j].x *= -1;
}
}
Arrays.sort(b, 0, cnt);
for (int j = 0; j < cnt;) {
int k = j;
while (k != cnt && b[j].x * b[k].y - b[j].y * b[k].x == 0) {
k++;
}
int cur = k - j;
j = k;
sub += cur * 1L * (cur - 1) / 2;
}
}
out.println(result - sub);
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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 CF().runIO();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | eb5392cc3f9ea244dbe694748c6e9e05 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.*;
public class CF {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int ans = 0;
for (int i = 0; i < n; i++) {
int dx = x[i], dy = y[i];
for (int j = 0; j < n; j++) {
x[j] -= dx;
y[j] -= dy;
}
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
ans += x[j] * y[k] != x[k] * y[j] ? 1 : 0;
}
}
}
out.println(ans);
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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 CF().runIO();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | a8da2a519d9445ab465bb2d2a2b8a657 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.*;
public class CF {
FastScanner in;
PrintWriter out;
class Point {
int x, y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
void solve() {
int n = in.nextInt();
Point[] a = new Point[n];
for (int i = 0; i < n; i++) {
a[i] = new Point(in.nextInt(), in.nextInt());
}
int ans = 0;
for (int i = 0; i < n; i++) {
int dx = a[i].x, dy = a[i].y;
for (int j = 0; j < n; j++) {
a[j].x -= dx;
a[j].y -= dy;
}
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
ans += a[j].x * a[k].y != a[k].x * a[j].y ? 1 : 0;
}
}
}
out.println(ans);
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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 CF().runIO();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 40e32939d8a12e41e539d275a8165168 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Vanya_Triangle {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int num=in.nextInt();
int[][] points=new int[num][2];
for(int i=0;i<num;i++)
{
points[i][0]=in.nextInt();
points[i][1]=in.nextInt();
}
Map<Map<Integer,Integer>,Integer> map=new HashMap<>();
int res=0;
for(int i=0;i<num;i++)
{
int counter=0;
int fixedcount=0;
//continous elimation of points
for(int j=i+1;j<num;j++)
{
if(points[i][0]==points[j][0])
{
int sx=0;
int sy=1;
Map<Integer,Integer> slope=new HashMap<>();
slope.put(sx, sy);
if(map.containsKey(slope))
{
map.put(slope, map.get(slope)+1);
}
else
{
map.put(slope, 1);
}
}
else
{
int dx=points[j][0]-points[i][0];
int dy=points[j][1]-points[i][1];
if(dy==0)
{
dx=1;
dy=0;
}
if(dx<0 && dy<0)
{
dx=Math.abs(dx);
dy=Math.abs(dy);
}
else if(dy<0)
{
dx=(-1)*dx;
dy=(-1)*dy;
}
int gcd=GCD(dx,dy);
int sx=dx/gcd;
int sy=dy/gcd;
Map<Integer,Integer> slope=new HashMap<>();
slope.put(sx, sy);
if(map.containsKey(slope))
{
map.put(slope, map.get(slope)+1);
}
else
{
map.put(slope, 1);
}
}
++counter;
}
for(Map.Entry<Map<Integer,Integer>, Integer> el:map.entrySet())
{
int value=el.getValue();
fixedcount=fixedcount+(counter-value)*value;
counter=counter-value;
}
map.clear();
res=res+fixedcount;
}
System.out.println(res);
}
private static int GCD(int dx, int dy) {
// TODO Auto-generated method stub
if(dx==0)
{
return 1;
}
if(dy==0)
{
return dx;
}
return GCD(dy,dx%dy);
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 3f2e1f72380d1422af0f30860927540e | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes |
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class MO {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Point[] p = new Point[n];
for(int i=0; i<n; i++) {
p[i] = new Point(in.nextInt(), in.nextInt());
}
Map<Line, Integer> map = new HashMap<>();
for(int i=1; i<n; i++) {
for(int j=0; j<i; j++) {
Point a = p[i];
Point b = p[j];
int num = a.y - b.y;
int den = a.x - b.x;
int fac = gcd((num), (den));
num /= fac;
den /= fac;
int yN = a.y*den - a.x*num;
Line l = new Line(num, den, yN);
map.put(l, map.getOrDefault(l, 0) + 2);
}
}
int[] pre = new int[n*n + 1];
for(int i=0; i<=n; i++) {
pre[i *(i-1)] = i;
}
long total = (long)n * (n-1) * (n-2);
total /= 6;
for(Entry<Line, Integer> e : map.entrySet()) {
int val = pre[e.getValue()];
long ans = (long)val * (val-1) * (val-2);
ans /= 6;
total -= ans;
}
System.out.println(total);
}
private static int gcd(int a, int b) {
if(b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
}
class Line {
int n;
int d;
int y;
public Line(int nn, int dd, int yy) {
n = nn;
d =dd;
y = yy;
}
@Override
public boolean equals(Object obj) {
Line s = (Line)obj;
return (n == s.n && d == s.d && y == s.y);
}
@Override
public int hashCode() {
return 113*n + 113*113*d + 113*113*113*113*y;
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | f89c8e407fa8d424af5d16f0f4a63688 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedOutputStream;
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 An Almost Retired Guy
*/
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);
VanyaAndTriangles solver = new VanyaAndTriangles();
solver.solve(1, in, out);
out.close();
}
static class VanyaAndTriangles {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] X = new int[n], Y = new int[n];
for (int i = 0; i < n; i++) {
X[i] = in.nextInt();
Y[i] = in.nextInt();
}
int ans = 0;
final int N = 200;
int[][] counter = new int[2 * N + 1][2 * N + 1];
ArrayList<EzIntIntPair> used = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int x = X[j] - X[i], y = Y[j] - Y[i];
if (y < 0) {
x *= -1;
y *= -1;
} else if (y == 0) x = Math.abs(x);
int g = (int) Euclid.gcd(x, y);
x /= g;
y /= g;
x += N;
y += N;
used.add(new EzIntIntPair(x, y));
counter[x][y]++;
}
int now = n - i - 1, temp = now * now;
while (!used.isEmpty()) {
EzIntIntPair pair = used.remove(used.size() - 1);
int x = pair.first, y = pair.second;
temp -= counter[x][y] * counter[x][y];
counter[x][y] = 0;
}
ans += temp / 2;
}
out.println(ans);
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(new BufferedOutputStream(outputStream));
}
public OutputWriter(Writer writer) {
super(writer);
}
public void close() {
super.close();
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
static class Euclid {
public static long gcd(long a, long b) {
return b == 0 ? Math.abs(a) : gcd(b, a % b);
}
}
static class EzIntIntPair implements Comparable<EzIntIntPair> {
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
public final int first;
public final int second;
public EzIntIntPair(int first, int second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EzIntIntPair that = (EzIntIntPair) o;
return first == that.first && second == that.second;
}
public int hashCode() {
int hash = HASHCODE_INITIAL_VALUE;
hash = (hash ^ PrimitiveHashCalculator.getHash(first)) * HASHCODE_MULTIPLIER;
hash = (hash ^ PrimitiveHashCalculator.getHash(second)) * HASHCODE_MULTIPLIER;
return hash;
}
public int compareTo(EzIntIntPair other) {
int cmpU = Integer.compare(first, other.first);
return cmpU != 0 ? cmpU : Integer.compare(second, other.second);
}
public String toString() {
return "(" + first + ", " + second + ")";
}
}
static final class PrimitiveHashCalculator {
private PrimitiveHashCalculator() {
}
public static int getHash(int x) {
return x;
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 5bff03d1d8d79229aff1014001c96c6d | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 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.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
InputReader inputReader = new InputReader(in);
PrintWriter out = new PrintWriter(System.out);
int n = inputReader.getNextInt();
Pair[] points = new Pair[n];
for(int i = 0; i < n; i++) {
points[i] = new Pair(inputReader.getNextInt(), inputReader.getNextInt());
}
Arrays.sort(points, Pair::compare);
long sol = 0;
for(int i = 2; i < n; i++) {
HashMap<Double, Integer> map = new HashMap<>();
for(int j = i-1; j >= 0; j--) {
double val = Math.atan2(points[i].y - points[j].y, points[i].x - points[j].x);
map.put(val, map.getOrDefault(val, 0) + 1);
}
sol = sol + (i - 1) * i;
for(Map.Entry<Double, Integer> entry: map.entrySet()) {
int val = entry.getValue();
sol = sol - val * (val - 1);
}
}
out.println(sol / 2);
in.close();
out.close();
}
public static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
static int compare(Pair p1, Pair p2) {
return (p1.x == p2.x) ? (p1.y - p2.y) : (p1.x - p2.x);
}
}
public static class InputReader {
static final String SEPARATOR = " ";
String[] split;
int head = 0;
BufferedReader in;
public InputReader(BufferedReader in) {
this.in = in;
}
private void fillBuffer() throws IOException {
if(split == null || head >= split.length) {
head = 0;
split = in.readLine().split(SEPARATOR);
}
}
public String getNextToken() throws IOException {
fillBuffer();
return split[head++];
}
public int getNextInt() throws IOException {
return Integer.parseInt(getNextToken());
}
public long getNextLong() throws IOException {
return Long.parseLong(getNextToken());
}
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 52f264eb9447bc9b7c82eaf9da4ae419 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
// ArrayList<Integer> lis = new ArrayList<Integer>();
// ArrayList<String> lis = new ArrayList<String>();
// PriorityQueue<P> que = new PriorityQueue<P>();
// PriorityQueue<Integer> que = new PriorityQueue<Integer>();
// Stack<Integer> stack = new Stack<Integer>();
//HashMap<Long,Long> map = new HashMap<Long,Long>();
// static long sum=0;
// 1000000007 (10^9+7)
//static int mod = 1000000007;
static long mod = 1000000007;
//static int mod = 1000000009; ArrayList<Integer> l[]= new ArrayList[n];
// static int dx[]={1,-1,0,0};
// static int dy[]={0,0,1,-1};
// //static int dx[]={1,-1,0,0,1,1,-1,-1};
//static int dy[]={0,0,1,-1,1,-1,1,-1};
//static Set<Integer> set = new HashSet<Integer>();
//static ArrayList<Integer> l[];
//static int parent[][],depth[],node,max_log;
//static ArrayList<Integer> l[];
public static void main(String[] args) throws Exception, IOException{
//Scanner sc =new Scanner(System.in);
Reader sc = new Reader(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();//m=sc.nextInt();
int d[][]=new int[n][2]; long r=0;
for( int i=0; i<n; i++ ){
d[i][0]=sc.nextInt();
d[i][1]=sc.nextInt();
}
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for( int i=0; i<n; i++ ){
r+=(long)(n-1)*(n-2)/2;
map.clear();
for( int t=0; t<n; t++ ){
if(i==t)continue;
int dx=d[t][0]-d[i][0];
int dy=d[t][1]-d[i][1];
int g=(int)gcd(abs(dx),abs(dy));
if(g>0){dx/=g; dy/=g;}
if(dx<0){dx*=-1; dy*=-1;}
int hs=10000*dx+dy;
if(dx==0)hs=1;
if(dy==0)hs=0;
Integer v=map.get(hs);
if(v==null){map.put(hs,1);}
else map.put(hs,v+1);
}
Iterator it = map.keySet().iterator();
while(it.hasNext()) {
int k=map.get(it.next());
r-=(long)k*(k-1)/2;
}
}
out.println(r/3);
out.flush();
// System.out.println(sb.append();
}
static long gcd(long a, long b){
if(min(a,b) == 0) return max(a,b);
return gcd(max(a, b) % min(a,b), min(a,b));
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
static boolean validpos(int x,int y,int r, int c){
return x<r && 0<=x && y<c && 0<=y;
}
static boolean bit(long x,int k){
// weather k-th bit (from right) be one or zero
return ( 0 < ( (x>>k) & 1 ) ) ? true:false;
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 265b245d5110a40c19e4cd6e9675c8d8 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | // package CF;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class D {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
Point [] p = new Point[n];
for (int i = 0; i < p.length; i++) {
p[i] = new Point(sc.nextInt(), sc.nextInt());
}
long ans = 0;
for (int i = 0; i < n; i++) {
ans += (n - i - 1) * (n - i - 2) / 2;
TreeMap<Line, Integer> lines = new TreeMap<>();
for (int j = i+1; j < n; j++) {
Line l = new Line(p[i], p[j]);
lines.put(l, lines.getOrDefault(l, 0)+1);
// System.out.println(i + " " + j + " " + l + " " + lines.get(l));
}
for(int l:lines.values()){
ans -= l * (l - 1) / 2;
}
}
out.println(ans);
out.flush();
out.close();
}
static class Point{
static final double EPS = 1e-9;
int x, y;
Point(int a, int b) { x = a; y = b; }
}
static class Line implements Comparable<Line> {
static final double INF = 1e9, EPS = 1e-9;
Point a, b; int mx, my;
Line(Point p, Point q) {
a = p;
b = q;
int dx = q.x - p.x, dy = q.y - p.y;
int g = gcd(dx, dy);
mx = dy / g; my = dx / g;
}
public int compareTo(Line s)
{
if(mx != s.mx)
return mx - s.mx;
return my - s.my;
}
static int gcd(int a, int b){
return b == 0?a:gcd(b, a%b);
}
}
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());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 8540e873fd03aefc53fa5bb74e4c0cc2 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static boolean eof = false;
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
tokenizer = null;
// reader = new BufferedReader(new FileReader("war.in"));
// writer = new PrintWriter(new FileWriter("war.out"));
reader = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1"));
writer = new PrintWriter(System.out);
banana();
reader.close();
writer.close();
}
static class Point {
int x, y;
Point(int _x, int _y) {
x = _x;
y = _y;
}
}
static int gcd(int x, int y) {
if (x % y == 0)
return y;
return gcd(y, x % y);
}
static int divider = 1000;
static void banana() throws IOException {
int n = nextInt();
if (n < 3) {
System.out.println(0);
return;
}
Point points[] = new Point[n];
for (int i = 0; i < n; ++i) {
points[i] = new Point(nextInt(), nextInt());
}
HashMap<Integer, Integer> mapka = new HashMap<Integer, Integer>();
int x[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
mapka.clear();
int zeroX = 0;
int zeroY = 0;
for (int j = 0; j < n; ++j) {
if (j == i)
continue;
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
if (dx != 0 && dy != 0) {
int key = (dx * divider + dy) / gcd(dx, dy);
mapka.put(key, mapka.getOrDefault(key, 0) + 1);
} else if (dx == 0) {
++zeroX;
} else
++zeroY;
}
for (Integer key : mapka.keySet())
x[mapka.get(key) + 1]++;
x[zeroX + 1]++;
x[zeroY + 1]++;
}
long val = ((long) n) * (n - 1) * (n - 2) / 6;
for (int i = 3; i <= n; ++i) {
int t = x[i] / i;
val -= t * (i-1) * (i-2) * i / 6;
}
System.out.println(val);
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 8a8ac378db5d8e26d4efce30803997ae | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Aldo Culquicondor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Point2DLong[] points = new Point2DLong[n];
for (int i = 0; i < n; ++i)
points[i] = new Point2DLong(in.nextInt(), in.nextInt());
Point2DLong[] tPoints = new Point2DLong[n-1];
long ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0, k = 0; j < n; ++j)
if (i != j)
tPoints[k++] = points[j].diff(points[i]).direction();
Arrays.sort(tPoints, (Point2DLong a, Point2DLong b)
-> Double.compare(a.pseudoAngle(), b.pseudoAngle()));
ans += count(tPoints);
}
out.println(ans / 3);
}
int count(Point2DLong[] points) {
int n = points.length, i = 0, j = 1, ans = 0;
while (i < n) {
int k = 1;
while (i + k < n && points[i + k].compareTo(points[i]) == 0)
++k;
j = Math.max(i + k, j);
while (j < i + n && points[i].cross(points[j % n]) > 0)
++j;
i += k;
ans += (j - i) * k;
}
return ans;
}
}
class InputReader {
private BufferedReader reader;
private 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());
}
}
class Point2DLong implements Comparable<Point2DLong> {
private long x, y;
private double angle, pseudoAngle;
public Point2DLong(long x, long y) {
this.x = x;
this.y = y;
this.angle = Double.NaN;
this.pseudoAngle = Double.NaN;
}
public Point2DLong diff(Point2DLong o) {
return new Point2DLong(x - o.x, y - o.y);
}
public Point2DLong direction() {
long g = gcd(Math.abs(x), Math.abs(y));
return new Point2DLong(x / g, y / g);
}
public long cross(Point2DLong o) {
return x * o.y - y * o.x;
}
public double pseudoAngle() {
if (Double.isNaN(pseudoAngle))
pseudoAngle = Math.copySign(1. - (double)x / (Math.abs(x) + Math.abs(y)), y);
return pseudoAngle;
}
public int compareTo(Point2DLong o) {
if (x == o.x)
return Long.compare(y, o.y);
return Long.compare(x, o.x);
}
private static long gcd(long a, long b) {
while (b != 0) {
long c = a % b;
a = b;
b = c;
}
return a;
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 3bef387fcec632edd80074a133a3475a | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Aldo Culquicondor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Point2DLong[] points = new Point2DLong[n];
for (int i = 0; i < n; ++i)
points[i] = new Point2DLong(in.nextInt(), in.nextInt());
Point2DLong[] tPoints = new Point2DLong[n-1];
long ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0, k = 0; j < n; ++j)
if (i != j)
tPoints[k++] = points[j].diff(points[i]).direction();
Arrays.sort(tPoints, (Point2DLong a, Point2DLong b)
-> Double.compare(a.getAngle(), b.getAngle()));
ans += count(tPoints);
}
out.println(ans / 3);
}
int count(Point2DLong[] points) {
int n = points.length, i = 0, j = 1, ans = 0;
while (i < n) {
int k = 1;
while (i + k < n && points[i + k].compareTo(points[i]) == 0)
++k;
j = Math.max(i + k, j);
while (j < i + n && points[i].cross(points[j % n]) > 0)
++j;
i += k;
ans += (j - i) * k;
}
return ans;
}
}
class InputReader {
private BufferedReader reader;
private 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());
}
}
class Point2DLong implements Comparable<Point2DLong> {
private long x, y;
private double angle;
public Point2DLong(long x, long y) {
this.x = x;
this.y = y;
angle = Double.NaN;
}
public Point2DLong diff(Point2DLong o) {
return new Point2DLong(x - o.x, y - o.y);
}
public Point2DLong direction() {
long g = gcd(Math.abs(x), Math.abs(y));
return new Point2DLong(x / g, y / g);
}
public long cross(Point2DLong o) {
return x * o.y - y * o.x;
}
public double getAngle() {
if (Double.isNaN(angle))
angle = Math.atan2(y, x);
return angle;
}
public int compareTo(Point2DLong o) {
if (x == o.x)
return Long.compare(y, o.y);
return Long.compare(x, o.x);
}
private static long gcd(long a, long b) {
while (b != 0) {
long c = a % b;
a = b;
b = c;
}
return a;
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | ec8451b68217dfa8c9e3f2f69388f2a9 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.*;
public class Ejercicio1{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] x = new int[2505];
int[] y = new int[2505];
sc.nextLine();
for (int i=0; i<n; i++){
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
triangles(n, x, y);
}
public static void triangles(int n, int[] x, int[] y){
int[] a = new int[4100005];
Map<Long,Integer> map = new HashMap<>();
//bruteforce because the pretty and smart solution didnt work as expected (see other sub)
for(int i=2; i<=2000; i++){
a[i*i-i] = i;
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i != j){
int kc = y[j] - y[i];
int kz = x[j] - x[i];
int bc = y[i]*(x[j] - x[i]) - x[i]*(y[j]-y[i]);
int bz = x[j] - x[i];
if(kz != 0){
int temp = gcd(Math.abs(kc), Math.abs(kz));
kc /= temp;
kz /= temp;
if(kc < 0){
kc = -kc; kz = -kz;
}
if(kc == 0){
kz = 1;
}
temp = gcd(Math.abs(bc), Math.abs(bz));
bc /= temp;
bz /= temp;
if(bc < 0){
bc = -bc; bz = -bz;
}
if(bc == 0){
bz = 1;
}
}
else{
kc = x[i];
bc = x[i];
}
long helper = (long)bc*270000*100000 + (long)bz*9000000 + (long)kc*300 + (long)kz;
int k = 0;
if(map.containsKey(helper)){
k = map.get(helper);
}
map.put(helper, k+2);
}
}
}
long res = ((long)n*(n-1)*(n-2))/6;
Iterator <Long> itr = map.keySet().iterator();
while (itr.hasNext()){
int temp = map.get(itr.next());
temp = a[temp/2];
res -= ((long)temp*(temp-1)*(temp-2))/6;
}
System.out.println(res);
}
public static int gcd(int a, int b){
if (b == 0) {
return a;
}
return gcd(b, a%b);
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | fb82e2f90c4a59d781c118242a98b3b6 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public void solve() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
for (int i = 0; i < N; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
long col = 0;
for (int i = 0; i < N; i++) {
// 点iが三角形に含まれる場合を考える
// ベクトルを列挙
ArrayList<Integer[]> vectors = new ArrayList<>(N - 1);
for (int j = 0; j < N; j++) {
if (j != i) {
vectors.add(new Integer[] { x[j] - x[i], y[j] - y[i] });
}
}
Collections.sort(vectors, areaComparator);
for (int j = 0; j < N - 1;) {
int k = j;
while (k < N - 1) {
int x1 = vectors.get(j)[0];
int y1 = vectors.get(j)[1];
int x2 = vectors.get(k)[0];
int y2 = vectors.get(k)[1];
if (x1 * y2 - y1 * x2 == 0 && x1 * x2 + y1 * y2 > 0) {
k++;
} else {
break;
}
}
col += (long) (k - j) * (k - j - 1);
j = k;
}
}
// N個の中から3つの点を選ぶ組み合わせの数
long all = (long) N * (N - 1) * (N - 2) / 6;
System.out.println(all - col / 4);
}
public Comparator<Integer[]> areaComparator = new Comparator<Integer[]>() {
public int compare(Integer[] a, Integer[] b) {
long ax = a[0], ay = a[1];
long bx = b[0], by = b[1];
int za = ay > 0 || (ay == 0 && ax > 0) ? 0 : 1;
int zb = by > 0 || (by == 0 && bx > 0) ? 0 : 1;
if (za != zb)
return za - zb;
return Long.signum(ay * bx - ax * by);
}
};
public static void main(String[] args) {
new Main().solve();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | fd5d78a412517d023f7319aaef29e693 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
private final double EPS = 1e-10;
public void solve() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
for (int i = 0; i < N; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
long sum = 0;
for (int i = 0; i < N; i++) {
// 点iが三角形に含まれる場合を考える
// ベクトルを列挙
ArrayList<Vector> vectors = new ArrayList<>();
for (int j = i + 1; j < N; j++) {
if (j != i) {
int vx = x[j] - x[i];
int vy = y[j] - y[i];
if (vx != 0 || vy != 0) {
vectors.add(new Vector(vx, vy));
}
}
}
int M = vectors.size();
long all = (long) M * (M - 1) / 2;
Collections.sort(vectors);
int j = 0;
while (j < vectors.size()) {
int k = j;
while (k < vectors.size() && Math.abs(vectors.get(j).rad - vectors.get(k).rad) < EPS) {
k++;
}
all -= (long) (k - j) * (k - j - 1) / 2;
j = k;
}
sum += all;
}
System.out.println(sum);
}
private class Vector implements Comparable<Vector> {
double rad;
int x, y;
public Vector(int vx, int vy) {
this.x = vx;
this.y = vy;
this.rad = Math.atan2(vy, vx);
if (this.rad <= 0) {
this.rad += Math.PI;
}
}
@Override
public int compareTo(Vector o) {
if (this.rad - o.rad > EPS) {
return 1;
} else if (o.rad - this.rad > EPS) {
return -1;
}
return 0;
}
}
public static void main(String[] args) {
new Main().solve();
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 689d699e86bf2bd33b0a01c544f3ca1e | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public void solve() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
for (int i = 0; i < N; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
long col = 0;
for (int i = 0; i < N; i++) {
int[][] lco = new int[N - 1][2];
int cur = 0;
for (int j = 0; j < N; j++) {
if (j != i) {
lco[cur][0] = x[j] - x[i];
lco[cur][1] = y[j] - y[i];
cur++;
}
}
Arrays.sort(lco, compArgi);
for (int j = 0; j < N - 1;) {
int k = j;
while (k < N - 1 && lco[j][0] * lco[k][1] - lco[j][1] * lco[k][0] == 0
&& lco[j][0] * lco[k][0] + lco[j][1] * lco[k][1] > 0)
k++;
col += (long) (k - j) * (k - j - 1);
j = k;
}
}
long all = (long) N * (N - 1) * (N - 2) / 6;
System.out.println(all - col / 4);
}
public static Comparator<int[]> compArgi = new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
long ax = a[0], ay = a[1];
long bx = b[0], by = b[1];
int za = ay > 0 || (ay == 0 && ax > 0) ? 0 : 1;
int zb = by > 0 || (by == 0 && bx > 0) ? 0 : 1;
if (za != zb)
return za - zb;
return Long.signum(ay * bx - ax * by);
}
};
public static void main(String[] args) {
new Main().solve();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | e569f64f55a8f9845657ea1170a67fe8 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public void solve() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
for (int i = 0; i < N; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
long col = 0;
for (int i = 0; i < N; i++) {
int[][] vectors = new int[N - 1][2];
int cur = 0;
for (int j = 0; j < N; j++) {
if (j != i) {
vectors[cur][0] = x[j] - x[i];
vectors[cur][1] = y[j] - y[i];
cur++;
}
}
Arrays.sort(vectors, compArgi);
for (int j = 0; j < N - 1;) {
int k = j;
while (k < N - 1 && vectors[j][0] * vectors[k][1] - vectors[j][1] * vectors[k][0] == 0
&& vectors[j][0] * vectors[k][0] + vectors[j][1] * vectors[k][1] > 0) {
k++;
}
col += (long) (k - j) * (k - j - 1);
j = k;
}
}
long all = (long) N * (N - 1) * (N - 2) / 6;
System.out.println(all - col / 4);
}
public Comparator<int[]> compArgi = new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
long ax = a[0], ay = a[1];
long bx = b[0], by = b[1];
int za = ay > 0 || (ay == 0 && ax > 0) ? 0 : 1;
int zb = by > 0 || (by == 0 && bx > 0) ? 0 : 1;
if (za != zb)
return za - zb;
return Long.signum(ay * bx - ax * by);
}
};
public static void main(String[] args) {
new Main().solve();
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 02c64ecbdc52a6406d0f580d9df5cd91 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
private final double EPS = 1e-10;
public void solve() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
for (int i = 0; i < N; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
long sum = 0;
for (int i = 0; i < N; i++) {
// 点iが三角形に含まれる場合を考える
// ベクトルを列挙
ArrayList<Double> rads = new ArrayList<>();
for (int j = i + 1; j < N; j++) {
if (j != i) {
int vx = x[j] - x[i];
int vy = y[j] - y[i];
if (vx != 0 || vy != 0) {
double rad = Math.atan2(vy, vx);
if (rad <= 0) {
rad += Math.PI;
}
rads.add(rad);
}
}
}
int M = rads.size();
long all = (long) M * (M - 1) / 2;
Collections.sort(rads);
int j = 0;
while (j < rads.size()) {
int k = j;
while (k < rads.size() && Math.abs(rads.get(j) - rads.get(k)) < EPS) {
k++;
}
all -= (long) (k - j) * (k - j - 1) / 2;
j = k;
}
sum += all;
}
System.out.println(sum);
}
public static void main(String[] args) {
new Main().solve();
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 1e3f1ff3e09c1a2007b1d4491906139f | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.Arrays;
/**
* Created by zhangliang on 15/9/18.
*/
public class Main {
private static int[] xx;
private static int[] yy;
private static long ans;
private static int[][] a = new int[440][440];
private static void input() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader( System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( System.out));
String str, strs[];
int n, x, y;
str = reader.readLine();
n = Integer.parseInt(str);
init( n);
for (int i = 0; i < n; ++i) {
strs = reader.readLine().split(" ");
xx[i] = Integer.parseInt(strs[0]);
yy[i] = Integer.parseInt( strs[1]);
}
for (int i = 0; i < n; ++i) {
for (int t = 0; t < 440; ++t)
Arrays.fill( a[t], 0);
for (int j = i + 1; j < n; ++j) {
int xDiff = xx[j] - xx[i];
int yDiff = yy[j] - yy[i];
if (xDiff < 0) {
xDiff *= -1;
yDiff *= -1;
}
if (xDiff == 0 && yDiff < 0) {
yDiff *= -1;
}
int t = gcd( xDiff, Math.abs( yDiff));
ans -= a[xDiff/t][yDiff/t + 200];
a[xDiff/t][yDiff/t + 200] ++;
}
}
writer.write( String.valueOf( ans));
close( reader, writer);
}
private static void init(int n) {
xx = new int[n];
yy = new int[n];
ans = (long)n * (n - 1) * (n - 2) / 6;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd( b, a%b);
}
private static void close(BufferedReader reader, BufferedWriter writer) {
try {
if (reader != null)
reader.close();
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
input();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 391dfb318232fc6064b6da2f9b60912b | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.*;
public class cf4 implements Runnable {
public static final String taskname = cf4.class.getName();
public StringTokenizer strtok;
public BufferedReader inr;
public PrintWriter out;
public static void main(String[] args) {
new Thread(new cf4()).start();
}
public void run() {
Locale.setDefault(Locale.US);
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
inr = new BufferedReader(oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader(taskname + ".in"));
out = new PrintWriter(oj ? new OutputStreamWriter(System.out, "ISO-8859-1") : new FileWriter(taskname + ".out"));
solve();
} catch (Exception e) {
if (!oj)
e.printStackTrace();
System.exit(9000);
} finally {
out.flush();
out.close();
}
}
public String nextToken() throws IOException {
while (strtok == null || !strtok.hasMoreTokens()) {
strtok = new StringTokenizer(inr.readLine());
}
return strtok.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
// Debugging
public static void printArray(boolean[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] ? '#' : '.');
}
System.out.print('\n');
}
}
// Solution
public void solve() throws NumberFormatException, IOException {
long n = nextLong();
int[] xs = new int[(int)n];
int[] ys = new int[(int)n];
for (int i = 0; i < n; i++) {
xs[i] = nextInt();
ys[i] = nextInt();
}
long bad = 0;
for (int i = 0; i < n - 2; i++) {
TreeMap<Fraction, Integer> m = new TreeMap<Fraction, Integer>();
for (int j = i + 1; j < n; j++) {
int dx = xs[i] - xs[j];
int dy = ys[i] - ys[j];
if (dy < 0 || (dy == 0 && dx < 0)) {
dx = -dx;
dy = -dy;
}
Fraction f = new Fraction(dx, dy);
m.put(f, m.containsKey(f) ? m.get(f) + 1 : 1);
}
for (long v : m.values()) {
if (v >= 2) {
bad += v * (v - 1) / 2;
}
}
}
out.print(n * (n - 1) * (n - 2) / 6 - bad);
}
}
class Fraction implements Comparable<Fraction> {
int a, b;
public Fraction(int a, int b) {
super();
this.a = a;
this.b = b;
}
public int compareTo(Fraction f) {
return this.a * f.b - this.b * f.a;
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 3b27ef7668fe339bbc38edc233781bd2 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
static final double EPS = 1e-9;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int ans = 0;
int n = sc.nextInt();
Point[] pts = new Point[n];
for (int i = 0; i < n; i++)
pts[i] = new Point(sc.nextInt(), sc.nextInt());
HashMap<Double, Integer> hm;
for (int i = 0; i < n; i++) {
int tot = 0;
hm = new HashMap<>();
for (int j = i + 1; j < n; j++) {
double slope = getSlope(pts[i], pts[j]) + EPS;
if (slope == Double.NEGATIVE_INFINITY) slope = Double.POSITIVE_INFINITY;
if (slope != Double.POSITIVE_INFINITY) slope *= 100000;
ans += tot - (hm.getOrDefault(slope, 0));
tot++;
hm.put(slope, hm.getOrDefault(slope, 0) + 1);
}
}
out.println(ans);
out.flush();
out.close();
}
static double sq(double x) {
return x * x;
}
static double getSlope(Point a, Point b) {
return ((double) (b.y - a.y)) / (b.x - a.x);
}
static class Vector {
int x, y;
Vector(Point a, Point b) {
x = b.x - a.x;
y = b.y - a.y;
}
double cross(Vector v) {
return x * v.y - y * v.x;
}
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
double distance(Point p) {
return Math.sqrt(sq(p.x - x) + sq(p.y - y));
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 2110f5cd18dd7fab9646f9ae200fafaa | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
static final double EPS = 1e-9;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int ans = 0;
int n = sc.nextInt();
Point[] pts = new Point[n];
for (int i = 0; i < n; i++)
pts[i] = new Point(sc.nextInt(), sc.nextInt());
TreeMap<Slope, Integer> hm;
for (int i = 0; i < n; i++) {
int tot = 0;
hm = new TreeMap<>();
for (int j = i + 1; j < n; j++) {
Slope slope = getSlope(pts[i], pts[j]);
ans += tot - (hm.getOrDefault(slope, 0));
tot++;
hm.put(slope, hm.getOrDefault(slope, 0) + 1);
}
}
out.println(ans);
out.flush();
out.close();
}
static double sq(double x) {
return x * x;
}
static Slope getSlope(Point a, Point b) {
if (a.y == b.y) return new Slope(0, 0);
int x = b.x - a.x;
int y = b.y - a.y;
int g = gcd(x, y);
return new Slope(x / g, y / g);
}
static int gcd(int n, int m) {
return (m == 0) ? n : gcd(m, n % m);
}
static class Slope implements Comparable<Slope> {
int x, y;
public Slope(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Slope o) {
return (x == o.x && y == o.y) ? 0 : (x == o.x) ? y - o.y : x - o.x;
}
}
static class Vector {
int x, y;
Vector(Point a, Point b) {
x = b.x - a.x;
y = b.y - a.y;
}
double cross(Vector v) {
return x * v.y - y * v.x;
}
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
double distance(Point p) {
return Math.sqrt(sq(p.x - x) + sq(p.y - y));
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 76a5bfb66ab77a7a303b8f4300d1da53 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.*;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
static final double EPS = 1e-9;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int ans = 0;
int n = sc.nextInt();
Point[] pts = new Point[n];
for (int i = 0; i < n; i++)
pts[i] = new Point(sc.nextInt(), sc.nextInt());
HashMap<Double, Integer> hm;
for (int i = 0; i < n; i++) {
int tot = 0;
hm = new HashMap<>();
for (int j = i + 1; j < n; j++) {
double slope = getSlope(pts[i], pts[j]) + EPS;
if (slope == Double.NEGATIVE_INFINITY) slope = Double.POSITIVE_INFINITY;
ans += tot - (hm.getOrDefault(slope, 0));
tot++;
hm.put(slope, hm.getOrDefault(slope, 0) + 1);
}
}
out.println(ans);
out.flush();
out.close();
}
static double sq(double x) {
return x * x;
}
static double getSlope(Point a, Point b) {
return ((double) (b.y - a.y)) / (b.x - a.x);
}
static class Vector {
int x, y;
Vector(Point a, Point b) {
x = b.x - a.x;
y = b.y - a.y;
}
double cross(Vector v) {
return x * v.y - y * v.x;
}
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
double distance(Point p) {
return Math.sqrt(sq(p.x - x) + sq(p.y - y));
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
} | Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 16652a10947f0547b6345e4bd759a390 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class VanyaTriangles {
void solve() {
int n = in.nextInt();
int[] x = new int[n], y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
// number of all triples
long ans = (long) n * (n - 1) * (n - 2);
for (int i = 0; i < n; i++) {
// for a given point i, count number of points j that pair (i, j) in the same line
int[][] c = new int[205][405];
for (int j = 0; j < n; j++) {
if (i != j) {
int dx = x[i] - x[j], dy = y[i] - y[j];
int[] key = getKey(dx, dy);
c[key[0]][key[1] + 200]++;
}
}
// subtract triples (i, j, k) that in the same line
for (int j = 0; j < 205; j++) {
for (int k = 0; k < 405; k++) {
if (c[j][k] > 1) {
ans -= (long) c[j][k] * (c[j][k] - 1);
}
}
}
}
// de-duplicate
out.println(ans / 6);
}
int[] getKey(int x, int y) {
int g = gcd(Math.abs(x), Math.abs(y));
x /= g;
y /= g;
if (x == 0) return new int[]{0, 1};
if (x < 0) return new int[]{-x, -y};
return new int[]{x, y};
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new VanyaTriangles().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | fa32714a26fae49bf160ef2b68079099 | train_002.jsonl | 1434645000 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. | 512 megabytes |
import java.util.*;
import java.io.*;
/**
*
* @author usquare
*
*/
public class ProblemA {
public static int mod = (int) (1e9+7);
public static InputReader in;
public static PrintWriter out;
public static void main(String[] args){
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n=in.nextInt();
long ans=n;
ans*=(n-1);
ans*=(n-2);
ans/=6;
long[] x=new long[n];
long[] y=new long[n];
for(int i=0;i<n;i++){
x[i]=in.nextInt();
y[i]=in.nextInt();
}
HashMap<Pair,Long> map=new HashMap<>();
long sum=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j) continue;
long a=y[j]-y[i];
long b=x[i]-x[j];
long c=-b*y[j]-a*x[j];
long g=gcd(a,gcd(b,c));
a/=g;
b/=g;
c/=g;
if(a<0 || (a==0 && b<0) || ( a==0 && b==0 && c<0)){
a*=-1;
b*=-1;
c*=-1;
}
Pair p=new Pair(a, b, c);
long tmp=0;
if(map.containsKey(p)) tmp+=map.get(p);
sum+=tmp;
map.put(p, tmp+1);
}
map.clear();
}
sum/=3;
ans-=sum;
out.println(ans);
out.close();
}
static class Pair implements Comparable<Pair>{
long x,y,i;
Pair (long x,long y,long i){
this.x=x;
this.y=y;
this.i=i;
}
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if(this.x!=o.x)
return Long.compare(this.x,o.x);
else
return Long.compare(this.y,o.y);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.i==i;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode()+new Long(i).hashCode()*37;
}
@Override
public String toString() {
return x+" "+y+" "+i;
}
}
public static class Merge {
public static void sort(int inputArr[]) {
int length = inputArr.length;
doMergeSort(inputArr,0, length - 1);
}
private static void doMergeSort(int[] arr,int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(arr,lowerIndex, middle);
doMergeSort(arr,middle + 1, higherIndex);
mergeParts(arr,lowerIndex, middle, higherIndex);
}
}
private static void mergeParts(int[]array,int lowerIndex, int middle, int higherIndex) {
int[] temp=new int[higherIndex-lowerIndex+1];
for (int i = lowerIndex; i <= higherIndex; i++) {
temp[i-lowerIndex] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (temp[i-lowerIndex] < temp[j-lowerIndex]) {
array[k] = temp[i-lowerIndex];
i++;
} else {
array[k] = temp[j-lowerIndex];
j++;
}
k++;
}
while (i <= middle) {
array[k] = temp[i-lowerIndex];
k++;
i++;
}
while(j<=higherIndex){
array[k]=temp[j-lowerIndex];
k++;
j++;
}
}
}
static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
public static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
public static long mul(long a,long b){
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
public static void rev(long[] a){
for(int i=0;i<a.length/2;i++){
long tmp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=tmp;
}
}
static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y){
if(y==0) return x;
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
static int gcd(int x,int y){
if(y==0) return x;
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
static int abs(int a,int b){
return (int)Math.abs(a-b);
}
static long abs(long a,long b){
return (long)Math.abs(a-b);
}
static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
InputReader(InputStream stream) {
this.stream = stream;
}
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++];
}
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;
}
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;
}
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] = nextInt();
}
return a;
}
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();
}
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();
}
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;
}
interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"] | 4 seconds | ["3", "1", "0"] | NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle. | Java 8 | standard input | [
"geometry",
"combinatorics",
"math",
"sortings",
"data structures",
"brute force"
] | d5913f8208efa1641f53caaee7624622 | The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane. Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide. | 1,900 | In the first line print an integer — the number of triangles with the non-zero area among the painted points. | standard output | |
PASSED | 0d273284d51b700963c81c88fb236f04 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhilash
*/
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 arr[][] = new int[n][m];
int sum = 0;
int rowSums[] = new int[n];
int colSums[] = new int[m];
for (int i = 0; i < n; i++) {
rowSums[i] = 0;
for (int j = 0; j < m; j++) {
arr[i][j] = in.nextInt();
sum += arr[i][j];
rowSums[i] += arr[i][j];
colSums[j] += arr[i][j];
}
}
if (sum == 0) {
out.println(0);
return;
}
int y, x;
int miny = 100000, minx = 1000000;
int minRows[] = new int[n];
int minCols[] = new int[m];
for (y = 0; n * y <= sum; y++) {
if ((sum - n * y) % m != 0)
continue;
x = (sum - n * y) / m;
int rows[] = new int[n];
int cols[] = new int[m];
boolean flag = true;
for (int i = 0; i < n; i++) {
if ((rowSums[i] < y) || (rowSums[i] - y) % m != 0) {
flag = false;
break;
} else {
rows[i] = (rowSums[i] - y) / m;
}
}
if (!flag)
continue;
for (int i = 0; i < m; i++) {
if ((colSums[i] < x) || (colSums[i] - x) % n != 0) {
flag = false;
break;
} else {
cols[i] = (colSums[i] - x) / n;
}
}
if (!flag)
continue;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (rows[i] + cols[j] != arr[i][j]) {
flag = false;
break;
}
}
if (!flag)
break;
}
if (flag && x + y < minx + miny) {
minx = x;
miny = y;
minRows = rows;
minCols = cols;
}
}
if (minx != 1000000) {
out.println(minx + miny);
for (int i = 0; i < n; i++) {
if (minRows[i] > 0)
for (int z = 0; z < minRows[i]; z++)
out.println("row " + (i + 1));
}
for (int i = 0; i < m; i++) {
if (minCols[i] > 0)
for (int z = 0; z < minCols[i]; z++)
out.println("col " + (i + 1));
}
return;
}
out.println(-1);
}
}
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());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | d977c83dcf05ccbcb108391b993c3f60 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | /*
* DA-IICT
* Author: Jugal Kalal
*/
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class HackerEarth{
static long MOD=(long)Math.pow(10,9)+7;
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try{
solve();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static InputReader in;
static PrintWriter w;
static void solve(){
in = new InputReader(System.in);
w = new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
long arr[][]=new long[n][m];
long arr1[][]=new long[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
arr[i][j]=in.nextLong();
arr1[i][j]=arr[i][j];
}
}
//rowfirst
int count=0;
ArrayList<String> ans=new ArrayList<>();
for(int i=0;i<n;i++){
long min=Long.MAX_VALUE;
for(int j=0;j<m;j++){
min=min<arr[i][j]?min:arr[i][j];
}
if(min>0){
count+=min;
for(int j=0;j<min;j++){
ans.add("row "+(i+1));
}
for(int j=0;j<m;j++){
arr[i][j]-=min;
}
}
}
//secondcolumn
for(int j=0;j<m;j++){
long min=Long.MAX_VALUE;
for(int i=0;i<n;i++){
min=min<arr[i][j]?min:arr[i][j];
}
if(min>0){
count+=min;
for(int i=0;i<min;i++){
ans.add("col "+(j+1));
}
for(int i=0;i<n;i++){
arr[i][j]-=min;
}
}
}
//firstcolumn
int count1=0;
ArrayList<String> ans1=new ArrayList<>();
for(int j=0;j<m;j++){
long min=Long.MAX_VALUE;
for(int i=0;i<n;i++){
min=min>arr1[i][j]?arr1[i][j]:min;
}
if(min>0){
count1+=min;
for(int i=0;i<min;i++){
ans1.add("col "+(j+1));
}
for(int i=0;i<n;i++){
arr1[i][j]-=min;
}
}
}
//secondrow
for(int i=0;i<n;i++){
long min=Long.MAX_VALUE;
for(int j=0;j<m;j++){
min=min<arr1[i][j]?min:arr1[i][j];
}
if(min>0){
count1+=min;
for(int j=0;j<min;j++){
ans1.add("row "+(i+1));
}
for(int j=0;j<m;j++){
arr1[i][j]-=min;
}
}
}
boolean flag=false;
boolean flag1=false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(arr[i][j]!=0){
flag=true;
}
if(arr1[i][j]!=0){
flag1=true;
}
}
}
if(flag&&flag1){
w.println("-1");
}else{
if(!flag&&!flag1){
if(count>count1){
w.println(count1);
for(int i=0;i<ans1.size();i++){
w.println(ans1.get(i));
}
}else{
w.println(count);
for(int i=0;i<ans.size();i++){
w.println(ans.get(i));
}
}
}else if(!flag1){
w.println(count1);
for(int i=0;i<ans1.size();i++){
w.println(ans1.get(i));
}
}else{
w.println(count);
for(int i=0;i<ans.size();i++){
w.println(ans.get(i));
}
}
}
}
static ArrayList<Integer> adj[]; //Adjacency Lists
static int V; // No. of vertices
// Constructor
static void Graph(int v){
V = v;
adj = new ArrayList[v];
for (int i=0; i<v; ++i){
adj[i] = new ArrayList();
}
}
// Function to add an edge into the graph
static void addEdge(int u,int v){
adj[u].add(v);
adj[v].add(u);
}
// static long[] isHamiltonian_path(int n){
// boolean dp[][]=new boolean[n][1<<n];
// long ans[]=new long[n];
// long sum[]=new long[n];
// for(int i=0;i<n;i++){
// dp[i][1<<i]=true;
// ans[i]=0;
// sum[i]=i+1;
// }
// for(int mask=0;mask<(1<<n);mask++){
// int s=0;
// int count=0,temp=mask;
// while(temp>0){
// s+=1+Math.log(temp&(-temp))/Math.log(2);
// temp=temp&(temp-1);
// count++;
// }
// for(int j=0;j<n;j++){
// if((mask&(1<<j))>0){
// for(int k=0;k<n;k++){
// if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
// dp[j][mask]=true;
// ans[j]=Math.max(ans[j],count-1);
// if(ans[j]==count-1){
// sum[j]=Math.max(sum[j], s);
// }
// }
// }
// }
// }
// }
// return sum;
// }
// static void bfs(int s,int n){
// boolean visited[]=new boolean[n];
// LinkedList<Integer> queue=new LinkedList<Integer>();
// queue.add(s);
// visited[s]=true;
// while(!queue.isEmpty()){
// int num=queue.pop();
//// System.out.println(ans.toString());
// for(int i=0;i<adj[num].size();i++){
// if(!visited[adj[num].get(i)]){
// visited[adj[num].get(i)]=true;
// queue.add(adj[num].get(i));
// }
// }
// }
// }
static long gcd(long a,long b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
static long power(long base, long exponent, long modulus){
long result = 1L;
while (exponent > 0) {
if (exponent % 2L == 1L)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
static HashMap<Long,Long> primeFactors(long n){
HashMap<Long,Long> ans=new HashMap<Long,Long>();
// Print the number of 2s that divide n
while (n%2L==0L)
{
if(ans.containsKey(2L)){
ans.put(2L,ans.get(2L)+1L);
}else{
ans.put(2L,1L);
}
n /= 2L;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2L)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(ans.containsKey(i)){
ans.put(i,ans.get(i)+1L);
}else{
ans.put(i,1L);
}
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
ans.put(n,1L);
return ans;
}
////for marking all prime numbers greater than 1 and less than equal to N
static void sieve(int N) {
boolean isPrime[]=new boolean[N+1];
isPrime[0] = true;
isPrime[1] = true;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
for(int j = i * i; j <= N ;j += i)
isPrime[j] = true;
}
}
}
// //if str2 (pattern) is subsequence of str1 (Text) or not
// static boolean function(String str1,String str2){
// str2 = str2.replace("", ".*"); //returns .*a.*n.*n.*a.
// return (str1.matches(str2)); // returns true
// }
static int Arr[];
static long size[];
//modified initialize function:
static void initialize(int N){
Arr=new int[N];
size=new long[N];
for(int i = 0;i<N;i++){
Arr[ i ] = i ;
size[ i ] = 1;
}
}
static boolean find(int A,int B){
if( root(A)==root(B) ) //if A and B have same root,means they are connected.
return true;
else
return false;
}
// modified root function.
static void weighted_union(int A,int B,int n){
int root_A = root(A);
int root_B = root(B);
if(size[root_A] < size[root_B ]){
Arr[ root_A ] = Arr[root_B];
size[root_B] += size[root_A];
}
else{
Arr[ root_B ] = Arr[root_A];
size[root_A] += size[root_B];
}
}
static int root (int i){
while(Arr[ i ] != i){
Arr[ i ] = Arr[ Arr[ i ] ] ;
i = Arr[ i ];
}
return i;
}
static boolean isPrime(long n) {
if(n < 2L) return false;
if(n == 2L || n == 3L) return true;
if(n%2L == 0 || n%3L == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1L;
for(long i = 6L; i <= sqrtN; i += 6L) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
// static HashMap<Integer,Integer> level;;
// static HashMap<Integer,Integer> parent;
static int maxlevel=0;
// static boolean T[][][];
// static void subsetSum(int input[], int total, int count) {
// T = new boolean[input.length + 1][total + 1][count+1];
// for (int i = 0; i <= input.length; i++) {
// T[i][0][0] = true;
// for(int j = 1; j<=count; j++){
// T[i][0][j] = false;
// }
// }
// int sum[]=new int[input.length+1];
// for(int i=1;i<=input.length;i++){
// sum[i]=sum[i-1]+input[i-1];
// }
// for (int i = 1; i <= input.length; i++) {
// for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
// for (int k = 1; k <= (int)Math.min(i,count); k++){
// if (j >= input[i - 1]) {//Exclude and Include
// T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
// } else {
// T[i][j][k] = T[i-1][j][k];
// }
// }
// }
// }
// }
// static <K,V extends Comparable<? super V>>
// SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
// SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
// new Comparator<Map.Entry<K,V>>() {
// @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
// int res = e2.getValue().compareTo(e1.getValue());
// return res != 0 ? res : 1;
// }
// }
// );
// sortedEntries.addAll(map.entrySet());
// return sortedEntries;
// }
//minimum prime factor of all the numbers less than n
static int minPrime[];
static void minimumPrime(int n){
minPrime=new int[n+1];
minPrime[1]=1;
for (int i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //If i is prime
for (int j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}
}
}
}
for (int i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}
}
}
static long modInverse(long A, long M)
{
long x=extendedEuclid(A,M)[0];
return (x%M+M)%M; //x may be negative
}
static long[] extendedEuclid(long A, long B) {
if(B == 0) {
long d = A;
long x = 1;
long y = 0;
return new long[]{x,y,d};
}
else {
long arr[]=extendedEuclid(B, A%B);
long temp = arr[0];
arr[0] = arr[1];
arr[1] = temp - (A/B)*arr[1];
return arr;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
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 readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
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 | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 7597296cb8db4b38bcc7264c0c75802e | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes |
import java.util.*;
import java.io.*;
import java.lang.Math.*;
public class MainA {
public static int mod = 20000;
public static long[] val;
public static long[] arr;
static int max = (int) 1e9 + 7;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
int g[][]=new int[n][m];
int min[]=new int[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
g[i][j]=in.nextInt();
}
}
int a[]=new int[n];
int b[]=new int[m];
if(n<m)
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(j==0)
{
min[i]=g[i][j];
}
else
{
min[i]=Math.min(min[i], g[i][j]);
}
}
a[i]=min[i];
//out.println(i +" "+a[i]);
for(int j=0;j<m;j++)
{
if(g[i][j]>a[i])
{
if(i!=0)
{
out.println(-1);out.close();
return;
}
b[j]=g[i][j]-a[i];
for(int k=0;k<n;k++)
{
if(k!=i)
g[k][j]-=b[j];
}
}
}
}
else
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(j==0)
{
b[i]=g[j][i];
}
else
{
b[i]=Math.min(b[i], g[j][i]);
}
}
//out.println(i +" "+a[i]);
for(int j=0;j<n;j++)
{
if(g[j][i]>b[i])
{
if(i!=0)
{
out.println(-1);out.close();
return;
}
a[j]=g[j][i]-b[i];
for(int k=0;k<m;k++)
{
if(k!=i)
g[j][k]-=a[j];
}
}
}
}
}
int count=0;
for(int i=0;i<n;i++)
{
if(a[i]>0)count+=a[i];
}
for(int j=0;j<m;j++)
{
if(b[j]>0)count+=b[j];
}
out.println(count);
for(int i=0;i<n;i++)
{
while(a[i]-->0)
{
out.println("row "+(i+1));
}
}
for(int j=0;j<m;j++)
{
while(b[j]-->0)
{
out.println("col "+(j+1));
}
}
out.close();
}
static void swap(Pairs arr[], int i, int j) {
Pairs t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
static int partition(Pairs arr[], int l, int h) {
long x = arr[h].x;
int i = (l - 1);
for (int j = l; j <= h - 1; j++) {
if (arr[j].x <= x) {
i++;
// swap arr[i] and arr[j]
swap(arr, i, j);
}
}
// swap arr[i+1] and arr[h]
swap(arr, i + 1, h);
return (i + 1);
}
// Sorts arr[l..h] using iterative QuickSort
static void sort(Pairs arr[], int l, int h) {
// create auxiliary stack
int stack[] = new int[h - l + 1];
// initialize top of stack
int top = -1;
// push initial values in the stack
stack[++top] = l;
stack[++top] = h;
// keep popping elements until stack is not empty
while (top >= 0) {
// pop h and l
h = stack[top--];
l = stack[top--];
// set pivot element at it's proper position
int p = partition(arr, l, h);
// If there are elements on left side of pivot,
// then push left side to stack
if (p - 1 > l) {
stack[++top] = l;
stack[++top] = p - 1;
}
// If there are elements on right side of pivot,
// then push right side to stack
if (p + 1 < h) {
stack[++top] = p + 1;
stack[++top] = h;
}
}
}
static class Pairs implements Comparable<Pairs> {
long x;
int y;
Pairs(long a, int b) {
x = a;
y = b;
}
@Override
public int compareTo(Pairs o) {
// TODO Auto-generated method stub
if (x == o.x)
return Integer.compare(y, o.y);
else
return Long.compare(x, o.x);
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y) {
if (y == 0)
return x;
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x) {
if (a == 0) {
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
public static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
public static int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
public static int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
public static long max(long a, long b) {
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b) {
if (a > b)
return b;
else
return a;
}
public static long[][] mul(long a[][], long b[][]) {
long c[][] = new long[2][2];
c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
return c;
}
public static long[][] pow(long n[][], long p, long m) {
long result[][] = new long[2][2];
result[0][0] = 1;
result[0][1] = 0;
result[1][0] = 0;
result[1][1] = 1;
if (p == 0)
return result;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result = mul(result, n);
//System.out.println(result[0][0]);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (result[i][j] >= m)
result[i][j] %= m;
}
}
p >>= 1;
n = mul(n, n);
// System.out.println(1+" "+n[0][0]+" "+n[0][1]+" "+n[1][0]+" "+n[1][1]);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (n[i][j] >= m)
n[i][j] %= m;
}
}
}
return result;
}
public static long pow(long n, long p) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
p >>= 1;
n *= n;
}
return result;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 4a8fd27cd88e5a0aaeb4253a9e7fde15 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.*;
import java.util.*;
public class C
{
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
int n = sc.nextInt() , m = sc.nextInt() ;
int [][] g = new int [n][m];
for(int i = 0 ;i < n ; i++)
for(int j = 0 ; j < m ; j++)
g[i][j] = sc.nextInt() ;
Node node = (new Node(new int [n][m] , new StringBuilder())) ;
if(n > m)
{
outer :
while(true)
{
for(int j = 0 ; j < m ;j++)
if(node.checkCol(j, g))
{
node.incrementCol(j);
continue outer ;
}
for(int i = 0 ; i < n ;i++)
if(node.checkRow(i, g))
{
node.incrementRow(i);
continue outer ;
}
break ;
}
}
else
{
outer :
while(true)
{
for(int i = 0 ; i < n ;i++)
if(node.checkRow(i, g))
{
node.incrementRow(i);
continue outer ;
}
for(int j = 0 ; j < m ;j++)
if(node.checkCol(j, g))
{
node.incrementCol(j);
continue outer ;
}
break ;
}
}
if(node.reachTarget(g))
{
out.println(node.dist);
out.println(node.st);
}
else
out.println(-1);
out.flush();
out.close();
}
static class Node
{
int [][] mat ;
StringBuilder st ;
int dist = 0 ;
Node(int [][] mat , StringBuilder st)
{
this.mat = new int[mat.length][mat[0].length] ;
for(int i = 0 ; i < mat.length ;i++ )
for(int j = 0 ; j < mat[i].length ;j++ )
this.mat[i][j] = mat[i][j] ;
this.st = new StringBuilder().append(st) ;
}
boolean checkRow(int i , int [][] g)
{
boolean can = true ;
for(int j = 0 ; j < mat[i].length ; j++)
can &= mat[i][j] + 1 <= g[i][j] ;
return can ;
}
boolean reachTarget(int [][] g)
{
boolean can = true ;
for(int i = 0 ; i < g.length ; i++)
for(int j = 0 ; j < g[i].length ; j++)
can &= g[i][j] == mat[i][j] ;
return can ;
}
boolean checkCol(int j , int [][] g)
{
boolean can = true ;
for(int i = 0 ; i < mat.length ; i++)
can &= mat[i][j] + 1 <= g[i][j] ;
return can ;
}
void incrementRow(int i)
{
st.append("row").append(" ").append(i+1).append("\n");
for(int j = 0 ; j < mat[i].length ; j++)
mat[i][j] ++ ;
dist ++ ;
}
void incrementCol(int j )
{
st.append("col").append(" ").append(j+1).append("\n");
for(int i = 0 ; i < mat.length ; i++)
mat[i][j] ++ ;
dist ++ ;
}
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception { return Integer.parseInt(next()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
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;
}
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 74fb9fd78acbf53c4d906e13b4ada919 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C_419 {
InputStream is;
PrintWriter out;
int n;
long a[];
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
int arr[][];
int m = 0;
int ans = 0;
void solve() {
n = ni();
m = ni();
arr = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
arr[i][j] = ni();
}
int min = Integer.MAX_VALUE;
for (int i = 1; i <= m; i++)
min = Math.min(arr[1][i], min);
int val = Integer.MAX_VALUE;
int index = 0;
for (int i = 0; i <= min; i++) {
int t = check(clone(arr), n, m, i);
if (t < val) {
val = t;
index = i;
}
}
// out.println(val);
if (val != Integer.MAX_VALUE) {
String s = fun(clone(arr), n, m, index);
out.println(ans);
out.println(s);
} else
out.println(-1);
}
int[][] clone(int arr[][]) {
int temp[][] = new int[arr.length][arr[1].length];
for (int i = 1; i < temp.length; i++) {
for (int j = 1; j < temp[1].length; j++) {
temp[i][j] = arr[i][j];
}
}
return temp;
}
int check(int arr[][], int n, int m, int min) {
int ans = 0;
boolean flag = true;
for (int i = 1; i <= m; i++) {
arr[1][i] -= min;
}
ans += min;
for (int j = 1; j <= m; j++) {
int sub = arr[1][j];
for (int i = 1; i <= n; i++) {
arr[i][j] -= sub;
}
ans += sub;
}
for (int i = 1; i <= n; i++) {
boolean f = true;
for (int j = 1; j <= m; j++) {
if (arr[i][j] != arr[i][1] || arr[i][j] < 0) {
f = false;
}
}
flag = f & flag;
}
if (flag) {
for (int i = 1; i <= n; i++)
ans += arr[i][1];
} else
return Integer.MAX_VALUE;
return ans;
}
String fun(int arr[][], int n, int m, int min) {
tr(arr);
StringBuilder s = new StringBuilder();
ans = 0;
for (int i = 1; i <= m; i++)
arr[1][i] -= min;
ans += min;
for (int i = 1; i <= min; i++) {
s.append("row " + 1 + "\n");
}
for (int j = 1; j <= m; j++) {
int sub = arr[1][j];
for (int i = 1; i <= n; i++) {
arr[i][j] -= sub;
}
ans += sub;
for (int i = 1; i <= sub; i++) {
s.append("col " + (j) + "\n");
}
}
for (int i = 1; i <= n; i++) {
ans += arr[i][1];
for (int k = 1; k <= arr[i][1]; k++)
s.append("row " + i + "\n");
}
return s.toString();
}
void run() throws Exception {
String INPUT = "C:\\Users\\Admin\\Desktop\\input.txt";
is = oj ? System.in : new FileInputStream(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new C_419().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | eb162d3485805962f0eb27c59a25780e | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | 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 {
String INPUT = "3 2 4 91 94 92 97 97 99 92 94 93 97 95 96 90 10005";
public void solve(){
int n = ni();
int m = ni();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
mat[i][j] = ni();
}
}
int min = Integer.MAX_VALUE;
int[] minR = null;
int[] minC = null;
for (int s = 0; s <= mat[0][0]; s++){
int[] r = new int[n];
Arrays.fill(r, -1);
int[] c = new int[m];
Arrays.fill(c, -1);
r[0] = s;
boolean ok = true;
for (int i = 0; i < m; i++){
c[i] = mat[0][i] - r[0];
if (c[i] < 0){
ok = false;
break;
}
for (int j = 1; j < n; j++){
if (r[j] == -1){
r[j] = mat[j][i] - c[i];
if (r[j] < 0){
ok = false;
break;
}
} else if (r[j] != mat[j][i] - c[i]){
ok = false;
break;
}
}
if (!ok){
break;
}
}
if (ok){
int count = 0;
for (int i = 0; i < r.length; i++){
count += r[i];
}
for (int i = 0; i < c.length; i++){
count += c[i];
}
if (count < min){
min = count;
minR = r;
minC = c;
}
}
}
int temp = n;
n = m;
m = temp;
int[][] mm = new int[n][m];
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
mm[i][j] = mat[j][i];
}
}
mat = mm;
for (int s = 0; s <= mat[0][0]; s++){
int[] r = new int[n];
Arrays.fill(r, -1);
int[] c = new int[m];
Arrays.fill(c, -1);
r[0] = s;
boolean ok = true;
for (int i = 0; i < m; i++){
c[i] = mat[0][i] - r[0];
if (c[i] < 0){
ok = false;
break;
}
for (int j = 1; j < n; j++){
if (r[j] == -1){
r[j] = mat[j][i] - c[i];
if (r[j] < 0){
ok = false;
break;
}
} else if (r[j] != mat[j][i] - c[i]){
ok = false;
break;
}
}
if (!ok){
break;
}
}
if (ok){
int count = 0;
for (int i = 0; i < r.length; i++){
count += r[i];
}
for (int i = 0; i < c.length; i++){
count += c[i];
}
if (count < min){
min = count;
minR = c;
minC = r;
}
}
}
if (min < Integer.MAX_VALUE){
out.println(min);
int[] r = minR;
int[] c = minC;
for (int i = 0; i < r.length; i++){
for (int j = 0; j < r[i]; j++){
out.println("row " + (i + 1));
}
}
for (int i = 0; i < c.length; i++){
for (int j = 0; j < c[i]; j++){
out.println("col " + (i + 1));
}
}
return;
}
out.println(-1);
}
InputStream is;
PrintWriter out;
void run() throws Exception
{
is = System.in;
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 | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 0b0b38b733f36c4aa24b46554813b63f | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class C {
int N,M;
int[][] G;
public List<String> rowFirst(){
List<String> list = new ArrayList<>();
int[][] copy = new int[N][M];
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
copy[i][j] = G[i][j];
}
}
for(int i = 0;i < N;i++){
int min = Integer.MAX_VALUE;
for(int j = 0;j < M;j++){
min = Math.min(min,copy[i][j]);
}
for(int j = 0;j < M;j++){
copy[i][j] -= min;
}
for(int j = 0;j < min;j++){
list.add("row " + (i+1));
}
}
for(int j = 0;j < M;j++){
int min = Integer.MAX_VALUE;
for(int i = 0;i < N;i++){
min = Math.min(min,copy[i][j]);
}
for(int i = 0;i < N;i++){
copy[i][j] -= min;
}
for(int i = 0;i < min;i++){
list.add("col " + (j+1));
}
}
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
if(copy[i][j] > 0){
return null;
}
}
}
return list;
}
public List<String> colFirst(){
List<String> list = new ArrayList<>();
int[][] copy = new int[N][M];
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
copy[i][j] = G[i][j];
}
}
for(int j = 0;j < M;j++){
int min = Integer.MAX_VALUE;
for(int i = 0;i < N;i++){
min = Math.min(min,copy[i][j]);
}
for(int i = 0;i < N;i++){
copy[i][j] -= min;
}
for(int i = 0;i < min;i++){
list.add("col " + (j+1));
}
}
for(int i = 0;i < N;i++){
int min = Integer.MAX_VALUE;
for(int j = 0;j < M;j++){
min = Math.min(min,copy[i][j]);
}
for(int j = 0;j < M;j++){
copy[i][j] -= min;
}
for(int j = 0;j < min;j++){
list.add("row " + (i+1));
}
}
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
if(copy[i][j] > 0){
return null;
}
}
}
return list;
}
public void solve() {
N = nextInt();
M = nextInt();
G = new int[N][M];
for(int i = 0;i < N;i++){
for(int j = 0;j < M;j++){
G[i][j] = nextInt();
}
}
List<String> row = rowFirst();
List<String> col = colFirst();
if(row == null && col == null){
out.println(-1);
return;
}
List<String> ans = row;
if(ans == null || row.size() > col.size()){
ans = col;
}else{
ans = row;
}
out.println(ans.size());
for(String s : ans){
out.println(s);
}
}
public static void main(String[] args) {
out.flush();
new C().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | a7369ce3a608188c3c9644de31165b34 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// atharva washimkar
// Jun 17, 2017
public class CODEFORCES_816_C {
static int N, M;
static int[][] grid;
static Set<Integer>[] zr, zc;
static int todo;
public static void reducer (int n) {
for (int m = 0; m < M; ++m) {
--grid[n][m];
if (grid[n][m] == 0) {
zr[n].add (m);
zc[m].add (n);
--todo;
}
}
}
public static void reducec (int m) {
for (int n = 0; n < N; ++n) {
--grid[n][m];
if (grid[n][m] == 0) {
zr[n].add (m);
zc[m].add (n);
--todo;
}
}
}
public static void main (String[] t) throws IOException {
INPUT in = new INPUT (System.in);
PrintWriter out = new PrintWriter (System.out);
N = in.iscan ();
M = in.iscan ();
grid = new int[N][M];
zr = new HashSet[N];
zc = new HashSet[M];
for (int n = 0; n < N; ++n)
zr[n] = new HashSet<Integer> ();
for (int m = 0; m < M; ++m)
zc[m] = new HashSet<Integer> ();
for (int n = 0; n < N; ++n) {
for (int m = 0; m < M; ++m) {
grid[n][m] = in.iscan ();
if (grid[n][m] == 0) {
zr[n].add (m);
zc[m].add (n);
}
else {
++todo;
}
}
}
//out.println (Arrays.toString (zc));
//out.println (Arrays.toString (zr));
List<String> moves = new ArrayList<String> ();
boolean g = true;
out:
while (todo > 0) {
for (int n = 0; n < N; ++n) {
for (int m = 0; m < M; ++m) {
if (grid[n][m] != 0) {
if (!zc[m].isEmpty () && !zr[n].isEmpty ()) {
g = false;
//out.println (n + " " + m);
break out;
}
else if (zc[m].isEmpty () && zr[n].isEmpty ()) {
if (M - zr[n].size () < N - zc[m].size ()) {
reducec (m);
moves.add ("col " + (m + 1));
}
else {
reducer (n);
moves.add ("row " + (n + 1));
}
}
else if (zc[m].isEmpty ()) {
reducec (m);
moves.add ("col " + (m + 1));
}
else if (zr[n].isEmpty ()) {
reducer (n);
moves.add ("row " + (n + 1));
}
//for (int nn = 0; nn < N; ++nn)
// out.println (Arrays.toString (grid[nn]));
//out.println ();
//out.println (Arrays.toString (zc));
//out.println (Arrays.toString (zr));
}
}
}
}
if (g) {
out.println (moves.size ());
for (String s : moves)
out.println (s);
}
else {
out.println (-1);
}
//out.println (moves);
out.close ();
}
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c)) c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c)) c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c)) c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c)) c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int gcd (int a, int b) {
return b == 0 ? a : gcd (b, a % b);
}
public static int lcm (int a, int b) {
return a * b / gcd (a, b);
}
public static int fast_pow_mod (int b, int x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static int fast_pow (int b, int x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 5b49e144902b4d7b41ce2fc10e6363dd | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
public class Main {
private static FastReader sc = new FastReader(System.in);
private static OutputWriter out = new OutputWriter(System.out);
private static ArrayList<String> ans = new ArrayList<>();
public static void main(String[] args) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
if (n < m) {
checkRows(arr, n, m);
checkColumns(arr, n, m);
} else {
checkColumns(arr, n, m);
checkRows(arr, n, m);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] != 0) {
System.out.println(-1);
System.exit(0);
}
}
}
out.printLine(ans.size());
for (String s : ans) out.printLine(s);
out.close();
}
private static void checkRows(int[][] arr, int r, int c) {
for (int i = 0; i < r; i++) {
int min = min(arr[i]);
for (int j = 0; j < min; j++) {
ans.add("row " + (i + 1));
}
for (int j = 0; j < c; j++) arr[i][j] -= min;
}
}
private static void checkColumns(int[][] arr, int r, int c) {
for (int i = 0; i < c; i++) {
int min = min(getColumn(arr, i));
for (int j = 0; j < min; j++) {
ans.add("col " + (i + 1));
}
for (int j = 0; j < r; j++) arr[j][i] -= min;
}
}
private static int[] getColumn(int[][] arr, int c) {
int[] col = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
col[i] = arr[i][c];
}
return col;
}
private static int min(int[] arr) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) min = Math.min(min, arr[i]);
return min;
}
}
class FastReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
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 == ',') {
c = read();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String nextLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String nextLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return nextLine();
} else {
return readLine0();
}
}
public BigInteger nextBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 2b8e5b5fc6cd99cc00917ffdc9ddfa24 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by Christy on 8/8/2017.
*/
public class KarenAndGame {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
int c = scan.nextInt();
int count = 0;
StringBuilder sb = new StringBuilder();
int[][] arr = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
arr[i][j] = scan.nextInt();
}
}
out:
while (!valid(arr)) {
// System.err.println(".");
//see if row can be changed
if (r < c) {
for (int i = 0; i < r; i++) {
boolean changeRow = true;
for (int j = 0; j < c; j++) {
if (arr[i][j] <= 0) {
//System.err.println("changeRow false at i = " + i + " j = " + j);
changeRow = false;
break;
}
}
if (changeRow) {
for (int j = 0; j < c; j++) {
arr[i][j]--;
}
sb.append("row " + (i + 1) + "\n");
count++;
continue out;
}
}
//see if column changed
for (int j = 0; j < c; j++) {
boolean changeCol = true;
for (int i = 0; i < r; i++) {
if (arr[i][j] <= 0) {
changeCol = false;
break;
}
}
if (changeCol) {
for (int i = 0; i < r; i++) {
arr[i][j]--;
}
sb.append("col " + (j + 1) + "\n");
count++;
continue out;
}
}
System.out.print(-1);
System.exit(0);
}
else {
//see if column changed
for (int j = 0; j < c; j++) {
boolean changeCol = true;
for (int i = 0; i < r; i++) {
if (arr[i][j] <= 0) {
changeCol = false;
break;
}
}
if (changeCol) {
for (int i = 0; i < r; i++) {
arr[i][j]--;
}
sb.append("col " + (j + 1) + "\n");
count++;
continue out;
}
}
for (int i = 0; i < r; i++) {
boolean changeRow = true;
for (int j = 0; j < c; j++) {
if (arr[i][j] <= 0) {
//System.err.println("changeRow false at i = " + i + " j = " + j);
changeRow = false;
break;
}
}
if (changeRow) {
for (int j = 0; j < c; j++) {
arr[i][j]--;
}
sb.append("row " + (i + 1) + "\n");
count++;
continue out;
}
}
System.out.print(-1);
System.exit(0);
}
}
System.out.println(count);
System.out.println(sb.toString());
}
public static void print(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.err.print(arr[i][j] + " ");
}
System.err.println();
}
}
public static boolean valid(int[][] arr) {
//System.err.println("in valid...");
//print(arr);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
if (arr[i][j] != 0) {
//System.err.println("...false");
return false;
}
}
}
//System.err.println("true...");
return true;
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 7ef46f49926e9b8e00d656086517515b | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.util.*;
import javax.swing.text.AbstractDocument.LeafElement;
import java.io.*;
import java.lang.*;
import java.lang.Character.Subset;
import java.math.*;
public class cf3 {
static class pair implements Comparable<pair>
{
Long x,y;
pair(long x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
if(x!=o.x)
return x.compareTo(o.x);
else
return y.compareTo(o.y);
}
}
static long mod=1000000007;
static boolean prime[];
public static void main(String args[])
{
InputReader in=new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
int m=in.nextInt();
int n=in.nextInt();
int[][] arr=new int[m][n];
int[][] ans=new int[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=0;
ans[i][j]=in.nextInt();
}
}
ArrayList<String> list=new ArrayList<>();
boolean flag2=false;
if(m<n)
{
while(true)
{
if(check(arr,ans))
break;
if(flag2)
break;
flag2=true;
for(int i=0;i<m;i++)
{
while(row(arr,ans,i))
{
flag2=false;
for(int j=0;j<n;j++)
arr[i][j]++;
list.add("row "+Integer.toString(i+1));
}
}
for(int i=0;i<n;i++)
{
while(col(arr,ans,i))
{
flag2=false;
for(int j=0;j<m;j++)
arr[j][i]++;
list.add("col "+Integer.toString(i+1));
}
}
}
if(flag2)
pw.println("-1");
else
{
pw.println(list.size());
for(int i=0;i<list.size();i++)
pw.println(list.get(i));
}
}
else
{
while(true)
{
if(check(arr,ans))
break;
if(flag2)
break;
flag2=true;
for(int i=0;i<n;i++)
{
while(col(arr,ans,i))
{
flag2=false;
for(int j=0;j<m;j++)
arr[j][i]++;
list.add("col "+Integer.toString(i+1));
}
}
for(int i=0;i<m;i++)
{
while(row(arr,ans,i))
{
flag2=false;
for(int j=0;j<n;j++)
arr[i][j]++;
list.add("row "+Integer.toString(i+1));
}
}
}
if(flag2)
pw.println("-1");
else
{
pw.println(list.size());
for(int i=0;i<list.size();i++)
pw.println(list.get(i));
}
}
pw.flush();
}
public static boolean col(int[][] arr,int[][] ans,int j)
{
int m=arr.length;
for(int i=0;i<m;i++)
{
if(arr[i][j]>=ans[i][j])
return false;
}
return true;
}
public static boolean row(int[][] arr,int[][] ans,int i)
{
int m=arr[0].length;
for(int j=0;j<m;j++)
{
if(arr[i][j]>=ans[i][j])
return false;
}
return true;
}
public static boolean check(int[][] arr,int[][] ans)
{
int m=arr.length;
int n=arr[0].length;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(arr[i][j]!=ans[i][j])
return false;
}
}
return true;
}
public static int distance(int x,int y,int p,int q)
{
int a=(x-p)*(x-p);
int b=(y-q)*(y-q);
int dis=a+b;
return dis;
}
public static int bnum(int num)
{
int ans=0;
for(int i=31;i>=0;i--)
{
if((num&(1<<i))!=0)
{
ans+=Math.pow(10,i);
}
}
return ans;
}
public static int bsdown(int a[],int item)
{
int low=0,high=a.length-1,ans=-1;
while(low<=high)
{
int mid=low+(high-low)/2;
if(a[mid]<=item)
{
ans=mid;
low=mid+1;
}
else
high=mid-1;
}
return ans;
}
public static long inverse(long num)
{
return fastpow(num,mod-2,mod);
}
public static int bsupper(int a[],int item)
{
int low=0,high=a.length-1,ans=-1;
while(low<=high)
{
int mid=low+(high-low)/2;
if(a[mid]>=item)
{
ans=mid;
high=mid-1;
}
else
low=mid+1;
}
return ans;
}
public static boolean isprime(int n)
{
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
return false;
}
return true;
}
public static long fact(long a,long mod)
{
long ans=1;
for(int i=1;i<=a;i++)
{
ans*=i;
ans%=mod;
}
return ans%mod;
}
public static long ncr(long n,long r,long mod)
{
long nom=1,dom=1;
nom=(fact(n,mod))%mod;
dom=(fact(r,mod)*fact(n-r,mod))%mod;
return (nom*fastpow(dom,mod-2,mod))%mod;
}
public static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
public static void prime(int n)
{
prime[0]=true;
prime[1]=true;
for(int i=2;i*i<=n;i++)
{
if(prime[i])
continue;
for(int j=i;j*i<=n;j++)
{
prime[i*j]=true;
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static long fastpow(long a,long b,long mod)
{
long ans=1;
while(b!=0)
{
if(b%2==1)
{
ans=(ans*a)%mod;
}
a=(a*a)%mod;
b/=2;
}
return ans;
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 473ba63a9383cc27b8116ba5e35552d6 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 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.List;
import java.util.StringTokenizer;
public class Main {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer buffer;
private static class Point {
int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void solve() {
int n = ni(), m = ni();
int[][]g = new int[n][m];
for (int i=0;i<n;i++) {
for (int j=0;j<m;j++) {
g[i][j] = ni();
}
}
ArrayList<String>res = new ArrayList<>();
if (m>=n) {
for (int row = 0; row < n; row++) {
int min = g[row][0];
for (int col = 1; col < m; col++) min = Math.min(min, g[row][col]);
for (int x = 0; x < min; x++) res.add("row " + (row + 1));
for (int c = 0; c < m; c++) g[row][c] -= min;
}
for (int col = 0; col < m; col++) {
int min = g[0][col];
for (int row = 1; row < n; row++) min = Math.min(min, g[row][col]);
for (int x = 0; x < min; x++) res.add("col " + (col + 1));
for (int r = 0; r < n; r++) g[r][col] -= min;
}
} else {
for (int col = 0; col < m; col++) {
int min = g[0][col];
for (int row = 1; row < n; row++) min = Math.min(min, g[row][col]);
for (int x = 0; x < min; x++) res.add("col " + (col + 1));
for (int r = 0; r < n; r++) g[r][col] -= min;
}
for (int row = 0; row < n; row++) {
int min = g[row][0];
for (int col = 1; col < m; col++) min = Math.min(min, g[row][col]);
for (int x = 0; x < min; x++) res.add("row " + (row + 1));
for (int c = 0; c < m; c++) g[row][c] -= min;
}
}
boolean empty = true;
for (int i=0;i<n;i++) {
for (int j=0;j<m;j++) {
if(g[i][j]>0) {
empty = false;
break;
}
}
if (!empty) break;
}
if (empty) {
out.println(res.size());
for (String val: res) out.println(val);
} else out.println(-1);
}
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
static String next() {
while (buffer == null || !buffer.hasMoreElements()) {
try {
buffer = new StringTokenizer(in.readLine());
} catch (IOException e) {
//
}
}
return buffer.nextToken();
}
static int ni() {
return Integer.parseInt(next());
}
static long nl() {
return Long.parseLong(next());
}
static double nd() {
return Double.parseDouble(next());
}
static String ns() {
return next();
}
static int[] ni(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = Integer.parseInt(next());
return res;
}
static long[] nl(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++)
res[i] = Long.parseLong(next());
return res;
}
static double[] nd(int n) {
double[] res = new double[n];
for (int i = 0; i < n; i++)
res[i] = Double.parseDouble(next());
return res;
}
static String[] ns(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++)
res[i] = next();
return res;
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 36965b0f8eb293edc4a4d15d28a92170 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
while (sc.hasNext()) {
int n=sc.nextInt();
int m=sc.nextInt();
int[][]maze=new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
maze[i][j]=sc.nextInt();
}
}
boolean row=true;
if(n>m)row=false;
boolean flag=true;
ArrayList<String>list=new ArrayList<String>();
while(true){
int max=0;
int a=-1;
int b=-1;
boolean c=false;
for(int i=0;i<n;i++){
int num1=0;
for(int j=0;j<m;j++){
if(maze[i][j]>=1){
num1++;
c=true;
}
}
if(num1==m){
a=i;
break;
}
}
for(int i=0;i<m;i++){
int num1=0;
for(int j=0;j<n;j++){
if(maze[j][i]>=1){
num1++;
}
}
if(num1==n){
b=i;
break;
}
}
//pw.println(a+" "+b);
if(a==-1&&b==-1){
if(!c){
break;
}
else{
flag=false;
break;
}
}
if(row){
if(a>=0){
list.add("row "+(a+1));
for(int i=0;i<m;i++){
maze[a][i]--;
}
}else{
list.add("col "+(b+1));
for(int i=0;i<n;i++){
maze[i][b]--;
}
}
}else{
if(b>=0){
list.add("col "+(b+1));
for(int i=0;i<n;i++){
maze[i][b]--;
}
}else{
list.add("row "+(a+1));
for(int i=0;i<m;i++){
maze[a][i]--;
}
}
}
}
if(!flag)pw.println(-1);
else{
pw.println(list.size());
for(int i=0;i<list.size();i++){
pw.println(list.get(i));
}
}
pw.flush();
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean hasNext() {
while (!st.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
st = new StringTokenizer(line);
}
return true;
}
public String next() {
while(!st.hasMoreTokens()){
st=new StringTokenizer(nextLine());
}
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 = "";
try {
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 8ba0cf591ed0abcd3943a6fac43eb817 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.util.*;
public class q3
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
int w = sc.nextInt();
int [][] g = new int[h][w];
int [] rmin = new int[h];
int [] cmin = new int[w];
int min = 501,sum = 0,rsum = 0,csum = 0;
if(h<=w){
for(int i = 0;i<h;i++){
min = 501;
for(int j = 0;j<w;j++){
g[i][j] = sc.nextInt();
sum+=g[i][j];
if(g[i][j] < min){
min=g[i][j];
}
}
rmin[i] = min;
rsum+=rmin[i];
}
for(int i = 0;i<h;i++){
if(rmin[i]!=0){
for(int j = 0;j<w;j++){
g[i][j] -= rmin[i];
}
}
}
for(int i = 0;i<w;i++){
min = 501;
for(int j = 0;j<h;j++){
if(g[j][i] < min){
min=g[j][i];
}
}
cmin[i] = min;
csum+=cmin[i];
}
int ans = csum+rsum;
if(((csum*h)+(rsum*w))!=sum){
System.out.println(-1);
}
else{
System.out.println(ans);
for(int i = 0;i<h;i++){
if(rmin[i]!=0){
for(int j = 0;j<rmin[i];j++){
System.out.println("row "+(i+1));
}
}
}
for(int i = 0;i<w;i++){
if(cmin[i]!=0){
for(int j = 0;j<cmin[i];j++){
System.out.println("col "+(i+1));
}
}
}
}
}else{
for(int i = 0;i<h;i++){
for(int j = 0;j<w;j++){
g[i][j] = sc.nextInt();
sum+=g[i][j];
}
}
for(int i = 0;i<w;i++){
min = 501;
for(int j = 0;j<h;j++){
if(g[j][i] < min){
min = g[j][i];
}
}
cmin[i] = min;
csum+=cmin[i];
}
for(int i = 0;i<w;i++){
if(cmin[i]!=0){
for(int j = 0;j<h;j++){
g[j][i] -= cmin[i];
}
}
}
for(int i = 0;i<h;i++){
min = 501;
for(int j = 0;j<w;j++){
if(g[i][j] < min){
min=g[i][j];
}
}
rmin[i] = min;
rsum+=rmin[i];
}
int ans = csum+rsum;
if(((csum*h)+(rsum*w))!=sum){
System.out.println(-1);
}
else{
System.out.println(ans);
for(int i = 0;i<w;i++){
if(cmin[i]!=0){
for(int j = 0;j<cmin[i];j++){
System.out.println("col "+(i+1));
}
}
}
for(int i = 0;i<h;i++){
if(rmin[i]!=0){
for(int j = 0;j<rmin[i];j++){
System.out.println("row "+(i+1));
}
}
}
}
}
}
} | Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | dda7239685598ba065b1015bf6c480fd | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 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.List;
import java.util.StringTokenizer;
/**
*
* @author Don Li
*/
public class KarenGame2 {
int INF = (int) 1e9;
void solve() {
int n = in.nextInt(), m = in.nextInt();
int[][] g = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) g[i][j] = in.nextInt();
int first_row_min = g[0][0];
for (int j = 1; j < m; j++) first_row_min = Math.min(first_row_min, g[0][j]);
int ans = INF, cnt = -1;
int[] row = new int[n], col = new int[m];
L:
for (int k = 0; k <= first_row_min; k++) {
row[0] = k;
for (int j = 0; j < m; j++) col[j] = g[0][j] - k;
for (int i = 1; i < n; i++) row[i] = g[i][0] - col[0];
for (int i = 1; i < n; i++) {
if (row[i] < 0) continue L;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] != row[i] + col[j]) {
continue L;
}
}
}
int tot = 0;
for (int i = 0; i < n; i++) tot += row[i];
for (int j = 0; j < m; j++) tot += col[j];
if (tot < ans) {
ans = tot;
cnt = k;
}
}
if (ans == INF) {
out.println(-1);
return;
}
row[0] = cnt;
for (int j = 0; j < m; j++) col[j] = g[0][j] - cnt;
for (int i = 1; i < n; i++) row[i] = g[i][0] - col[0];
out.println(ans);
for (int i = 0; i < n; i++) {
for (int j = 0; j < row[i]; j++) {
out.printf("row %d%n", i + 1);
}
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < col[j]; i++) {
out.printf("col %d%n", j + 1);
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new KarenGame2().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | a7a94b72be48d265530d86dbedc55a90 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
*
* @author Don Li
*/
public class KarenGame3 {
int N = 110;
int n, m;
int[][] g;
int[] row = new int[N], col = new int[N];
void solve() {
n = in.nextInt();
m = in.nextInt();
g = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) g[i][j] = in.nextInt();
int[] p = findEmptyCell();
if (p != null && findPlan(p[0], p[1])) {
printPlan();
return;
}
if (n <= m) {
int min = g[0][0];
for (int j = 1; j < m; j++) min = Math.min(min, g[0][j]);
int y = -1;
for (int j = 0; j < m; j++) {
g[0][j] -= min;
if (g[0][j] == 0) y = j;
}
if (findPlan(0, y)) {
row[0] += min;
printPlan();
} else {
out.println(-1);
}
} else {
int min = g[0][0];
for (int i = 1; i < n; i++) min = Math.min(min, g[i][0]);
int x = -1;
for (int i = 0; i < n; i++) {
g[i][0] -= min;
if (g[i][0] == 0) x = i;
}
if (findPlan(x, 0)) {
col[0] += min;
printPlan();
} else {
out.println(-1);
}
}
}
int[] findEmptyCell() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 0) {
return new int[]{i, j};
}
}
}
return null;
}
boolean findPlan(int x, int y) {
for (int i = 0; i < n; i++) {
if (i != x) row[i] = g[i][y];
}
for (int j = 0; j < m; j++) {
if (j != y) col[j] = g[x][j];
}
for (int i = 0; i < n; i++) if (row[i] < 0) return false;
for (int j = 0; j < m; j++) if (col[j] < 0) return false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] != row[i] + col[j]) {
return false;
}
}
}
return true;
}
void printPlan() {
int tot = 0;
for (int i = 0; i < n; i++) tot += row[i];
for (int j = 0; j < m; j++) tot += col[j];
out.println(tot);
for (int i = 0; i < n; i++) {
for (int j = 0; j < row[i]; j++) {
out.printf("row %d%n", i + 1);
}
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < col[j]; i++) {
out.printf("col %d%n", j + 1);
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new KarenGame3().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | a7275fad90db089c8b288f5e17946860 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 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.Arrays;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class KarenGame {
void solve() {
int n = in.nextInt(), m = in.nextInt();
int[][] g = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) g[i][j] = in.nextInt();
List<String> rowFirst = new ArrayList<>();
int[] row_min = new int[n];
for (int i = 0; i < n; i++) {
row_min[i] = g[i][0];
for (int j = 1; j < m; j++) row_min[i] = Math.min(row_min[i], g[i][j]);
for (int j = 0; j < row_min[i]; j++) {
rowFirst.add("row " + (i + 1));
}
}
for (int j = 0; j < m; j++) {
int x = g[0][j] - row_min[0];
for (int i = 1; i < n; i++) {
if (g[i][j] - row_min[i] != x) {
out.println(-1);
return;
}
}
for (int i = 0; i < x; i++) {
rowFirst.add("col " + (j + 1));
}
}
List<String> colFirst = new ArrayList<>();
int[] col_min = new int[m];
for (int j = 0; j < m; j++) {
col_min[j] = g[0][j];
for (int i = 1; i < n; i++) col_min[j] = Math.min(col_min[j], g[i][j]);
for (int i = 0; i < col_min[j]; i++) {
colFirst.add("col " + (j + 1));
}
}
for (int i = 0; i < n; i++) {
int x = g[i][0] - col_min[0];
for (int j = 1; j < m; j++) {
if (g[i][j] - col_min[j] != x) {
out.println(-1);
return;
}
}
for (int j = 0; j < x; j++) {
colFirst.add("row " + (i + 1));
}
}
if (rowFirst.size() <= colFirst.size()) {
out.println(rowFirst.size());
for (String s : rowFirst) out.println(s);
} else {
out.println(colFirst.size());
for (String s : colFirst) out.println(s);
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new KarenGame().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 8b4e709ef9b2dd0a810146730d6519e3 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class KarenGame3 {
int N = 110;
int n, m;
int[][] g;
int[] row = new int[N], col = new int[N];
void solve() {
n = in.nextInt();
m = in.nextInt();
g = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) g[i][j] = in.nextInt();
if (findPlan()) {
printPlan();
return;
}
if (n <= m) {
int min = g[0][0];
for (int j = 1; j < m; j++) min = Math.min(min, g[0][j]);
for (int j = 0; j < m; j++) g[0][j] -= min;
if (findPlan()) {
row[0] += min;
printPlan();
} else {
out.println(-1);
}
} else {
int min = g[0][0];
for (int i = 1; i < n; i++) min = Math.min(min, g[i][0]);
for (int i = 0; i < n; i++) g[i][0] -= min;
if (findPlan()) {
col[0] += min;
printPlan();
} else {
out.println(-1);
}
}
}
boolean findPlan() {
boolean found = false;
L:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 0) {
found = true;
for (int r = 0; r < n; r++) {
if (r != i) row[r] = g[r][j];
}
for (int c = 0; c < m; c++) {
if (c != j) col[c] = g[i][c];
}
break L;
}
}
}
if (!found) return false;
for (int i = 0; i < n; i++) if (row[i] < 0) return false;
for (int j = 0; j < m; j++) if (col[j] < 0) return false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] != row[i] + col[j]) {
return false;
}
}
}
return true;
}
void printPlan() {
int tot = 0;
for (int i = 0; i < n; i++) tot += row[i];
for (int j = 0; j < m; j++) tot += col[j];
out.println(tot);
for (int i = 0; i < n; i++) {
for (int j = 0; j < row[i]; j++) {
out.printf("row %d%n", i + 1);
}
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < col[j]; i++) {
out.printf("col %d%n", j + 1);
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new KarenGame3().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 78ff81da11da84c0d0bcb8325d67d901 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class ProblemC3 {
BufferedReader rd;
ProblemC3() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
int n = intarr()[0];
int[][] c = new int[n][];
for(int i=0;i<n;i++) {
c[i] = intarr();
}
List<int[]> res1 = solve(deepcopy(c), true);
if(res1 == null) {
out(-1);
} else {
List<int[]> res2 = solve(deepcopy(c), false);
List<int[]> res = computeMoveCount(res1) < computeMoveCount(res2)?res1:res2;
int moveCount = computeMoveCount(res);
StringBuilder buf = new StringBuilder();
buf.append(moveCount);
for (int[] r : res) {
for (int i = 0; i < r[1]; i++) {
buf.append('\n').append(r[0] == 0 ? "row" : "col").append(' ').append(r[2]+1);
}
}
out(buf);
}
}
private int computeMoveCount(List<int[]> x) {
int moveCount = 0;
for (int[] r : x) {
moveCount += r[1];
}
return moveCount;
}
private int[][] deepcopy(int[][] c) {
int[][] res = new int[c.length][];
for(int i=0;i<c.length;i++) {
res[i] = copyOf(c[i], c[i].length);
}
return res;
}
private List<int[]> solve(int[][] c, boolean flip) {
int n = c.length;
int m = c[0].length;
List<int[]> res = new ArrayList<>();
for(int k=0;k<=2;k++) {
if(k==0 ^ flip) for (int i = 0; i < n; i++) {
int mi = 1000;
for (int j = 0; j < m; j++) {
mi = min(mi, c[i][j]);
}
if (mi > 0) {
res.add(new int[]{0, mi, i});
for (int j = 0; j < m; j++) {
c[i][j] -= mi;
}
}
}
if(k==1 ^ flip) for (int i = 0; i < m; i++) {
int mi = 1000;
for (int j = 0; j < n; j++) {
mi = min(mi, c[j][i]);
}
if (mi > 0) {
res.add(new int[]{1, mi, i});
for (int j = 0; j < n; j++) {
c[j][i] -= mi;
}
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(c[i][j] > 0) {
return null;
}
}
}
return res;
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
private String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemC3();
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | c93f9b5b54cd0c321fbfa1bc862dd02b | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* created by asheshvidyut on 17/06/17
**/
public class C {
public static void main(String args[]) {
try {
InputReader in = new InputReader(System.in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.readInt();
int m = in.readInt();
Vector<Integer> row = new Vector<Integer>();
Vector<Integer> col = new Vector<Integer>();
int minRow[] = new int[n];
Arrays.fill(minRow, Integer.MAX_VALUE);
int minCol[] = new int[m];
Arrays.fill(minCol, Integer.MAX_VALUE);
int mat[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = in.readInt();
minRow[i] = Math.min(mat[i][j], minRow[i]);
minCol[j] = Math.min(mat[i][j], minCol[j]);
}
}
int rowSub[] = new int[n];
int colSub[] = new int[m];
boolean ans = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] -= rowSub[i];
mat[i][j] -= colSub[j];
while (mat[i][j] > 0) {
boolean rowDel = true;
boolean colDel = true;
if (minRow[i] - 1 < 0)
rowDel = false;
if (minCol[j] - 1 < 0)
colDel = false;
if (rowDel && colDel) {
if (n < m) {
minRow[i]--;
rowSub[i]++;
row.add(i);
mat[i][j]--;
}
else {
minCol[j]--;
colSub[j]++;
col.add(j);
mat[i][j]--;
}
}
else if (rowDel) {
minRow[i]--;
rowSub[i]++;
row.add(i);
mat[i][j]--;
}
else if(colDel) {
minCol[j]--;
colSub[j]++;
col.add(j);
mat[i][j]--;
}
else {
ans = false;
break;
}
minRow[i] = Math.min(mat[i][j], minRow[i]);
minCol[j] = Math.min(mat[i][j], minCol[j]);
}
}
}
boolean allzero = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] != 0) {
allzero = false;
}
}
}
if (ans && allzero) {
out.write(Integer.toString(row.size() + col.size()));
out.newLine();
for(int id: row) {
out.write("row " + Integer.toString(id + 1));
out.newLine();
}
for (int id: col) {
out.write("col " + Integer.toString(id + 1));
out.newLine();
}
}
else {
out.write(Integer.toString(-1));
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int length = readInt();
if (length < 0)
return null;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
bytes[i] = (byte) read();
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public boolean readBoolean() {
return readInt() == 1;
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 5764e5dac115aad7d05abd66c0cd5f49 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes |
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by imahmoud on 5/13/17.
*/
public class C {
public void solve(){
Scanner in = new Scanner(System.in);
int N1 = in.nextInt();
int N2 = in.nextInt();
int[][] grid;
int W,H;
boolean rotated =false;
if(N1 < N2){
W = N1;
H = N2;
grid = new int[W][H];
for (int i = 0; i < N1; i++) {
for (int j = 0; j < N2; j++) {
grid[i][j] = in.nextInt();
}
}
}else{
rotated = true;
W = N2;
H = N1;
grid = new int[W][H];
for (int i = 0; i < N1; i++) {
for (int j = 0; j < N2; j++) {
grid[j][i] = in.nextInt();
}
}
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < H; j++) {
min = Math.min(min,grid[0][j]);
}
List<String> res = new ArrayList<>();
for (int i = 0; i < H; i++) {
int diff = grid[0][i] - min;
for (int j = 0; j < diff; j++) {
res.add((rotated ? "row " : "col ")+ (i+1));
for (int f = 0; f < W; f++) {
grid[f][i]--;
}
}
}
for (int i = 0; i < W; i++) {
int diff = grid[i][0];
for (int j = 1; j < H; j++) {
if(grid[i][j] != diff){
System.out.println(-1);
return;
}
}
for (int j = 0; j < diff; j++) {
res.add((rotated ? "col ": "row ")+ (i+1));
}
}
System.out.println(res.size());
for (int i = 0; i < res.size(); i++) {
System.out.println(res.get(i));
}
}
public static void main(String[] args) {
new C().solve();
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 219c39e59dcbbbe4bdd2cc566e64d7d2 | train_002.jsonl | 1497710100 | On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! | 512 megabytes | //package cf816;
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.Reader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class C {
static int a[][], N, M;
static ArrayList<Integer> r, c;
public static void main(String[] args) throws FileNotFoundException {
InputStream is = System.in;
// is = new FileInputStream(new File("A.txt"));
FastScanner sc = new FastScanner(new InputStreamReader(is));
r=new ArrayList<Integer>();
c=new ArrayList<Integer>();
N = sc.nextInt();
M = sc.nextInt();
a=new int[N][M];
for (int i=0; i<N; i++)
for (int j=0; j<M; j++) a[i][j]=sc.nextInt();
if (N<M) {
row(); col();
} else {
col(); row();
}
for (int i=0; i<N; i++)
for (int j=0; j<M; j++)
if (a[i][j]>0) {
System.out.println(-1);
System.exit(0);
}
System.out.println(r.size()+c.size());
for (int rr:r) {
System.out.println("row "+(rr+1));
}
for (int rr:c) {
System.out.println("col "+(rr+1));
}
}
static void col() {
for (int i=0; i<M; i++) {
int min=1001;
for (int j=0; j<N; j++) {
min=Math.min(a[j][i],min);
}
for (int j=0; j<N; j++) a[j][i]-=min;
while(min-->0) c.add(i);
}
}
static void row() {
for (int i=0; i<N; i++) {
int min=1001;
for (int j=0; j<M; j++) {
min=Math.min(a[i][j],min);
}
for (int j=0; j<M; j++) a[i][j]-=min;
while(min-->0) r.add(i);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(Reader in) {
br = new BufferedReader(in);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"] | 2 seconds | ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"] | NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3. | Java 8 | standard input | [
"implementation",
"greedy",
"brute force"
] | b19ab2db46484f0c9b49cf261502bf64 | The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500). | 1,700 | If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. | standard output | |
PASSED | 4b67735a4cf134836995eaa4b9d2c395 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author dima
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int[] leftCount;
int[] rightCount;
public void solve(int testNumber, Scanner in, PrintWriter out) {
String str = in.nextLine();
final int N = str.length();
leftCount = new int[N];
rightCount = new int[N];
leftCount[0] = str.charAt(0) == 'b' ? 1 : 0;
rightCount[N - 1] = str.charAt(N - 1) == 'b' ? 1 : 0;
int[] aCount = new int[N];
aCount[0] = str.charAt(0) == 'a' ? 1 : 0;
for (int i = 1; i < str.length(); ++i) {
leftCount[i] =
leftCount[i - 1] + (str.charAt(i) == 'b' ? 1 : 0);
aCount[i] = aCount[i - 1] + (str.charAt(i) == 'a' ? 1 : 0);
}
for (int j = N - 2; j >= 0; --j) {
rightCount[j] =
rightCount[j + 1] + (str.charAt(j) == 'b' ? 1 : 0);
}
int minDel = Integer.min(leftCount[N - 1], aCount[N - 1]);
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
int middle = aCount[j];
if (i > 0) {
middle -= aCount[i - 1];
}
int left = i > 0 ? leftCount[i - 1] : 0;
int right = j != N - 1 ? rightCount[j + 1] : 0;
minDel = Integer.min(minDel, left + middle + right);
}
}
out.print(N - minDel);
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | bc07fa8ca08eb169cf65eeb24858a320 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
Reader.init(System.in);
StringBuilder out = new StringBuilder();
char[] c = (" " + Reader.next()).toCharArray();
int[] a = new int[c.length], b = new int[c.length];
for(int i = 1; i < c.length; i++) {
a[i] = a[i - 1];
b[i] = b[i - 1];
if(c[i] == 'a')
a[i]++;
else b[i]++;
}
int max = 0;
for(int i = 0, j; i < c.length; i++)
for(j = i; j < c.length; j++)
max = Math.max(max, a[i] + (b[j] - b[i]) + (a[c.length - 1] - a[j]));
out.append(max).append('\n');
PrintWriter pw = new PrintWriter(System.out);
pw.print(out);
pw.close();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8"));
tokenizer = new StringTokenizer("");
}
static void init(String url) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(url));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 2a8d7feb28ca29a49831d88738439c1c | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.*;
import java.util.*;
public class C
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder out=new StringBuilder("");
StringTokenizer st;
String s=br.readLine();
int n=s.length();
int[] a=new int[n+1], b=new int[n+1];
for(int i=1;i<=n;i++) {
a[i]=a[i-1];
b[i]=b[i-1];
if(s.charAt(i-1)=='a') a[i]++;
else b[i]++;
}
int res=0, r1,r2,r;
for(int i=1;i<=n;i++)
for(int j=i;j<=n;j++) {
r1 = a[i]+ b[j]-b[i]+ a[n]-a[j];
r2 = b[j]+ a[n]-a[j];
r =(int)Math.max(r1,r2);
res=(int)Math.max(res,r);
}
System.out.print(res);
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | ef9825ba3e6bc2fbacad6557d66db90e | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes |
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
static String s;
static int[][] dp;
static int solve(int st, int i) {
if(i == s.length() || st > 2)
return 0;
if(dp[st][i] != -1)
return dp[st][i];
int req = st % 2;
int ans = solve(st + 1, i);
if((char)('a' + req) == s.charAt(i)) {
ans = Math.max(ans, 1 + solve(st, i + 1));
}
else
ans = Math.max(ans, solve(st, i + 1));
return dp[st][i] = ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
s = sc.next();
dp = new int[3][s.length()];
Arrays.fill(dp[0], -1);
Arrays.fill(dp[1], -1);
Arrays.fill(dp[2], -1);
int ans = solve(0, 0);
for(int i = 1; i < s.length(); i++)
ans = Math.max(ans, solve(0, i));
System.out.println(ans);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 4c825ce67c3861a8a8bc3577fc64278b | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.math.BigDecimal;
import java.math.BigInteger;
public class JavaApplication9 {
//***************************************************************************************
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();
}
}
//****************************************************************************************
static boolean isp(long n)
{
if(n==3||n==2)
return true;
if(n%2==0||n%3==0||n==1)
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 int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
} */
/* public int BinaryToDecimal(int binaryNumber){
int decimal = 0;
int p = 0;
while(true){
if(binaryNumber == 0){
break;
} else {
int temp = binaryNumber%10;
decimal += temp*Math.pow(2, p);
binaryNumber = binaryNumber/10;
p++;
}
}
return decimal;
}*/
/*-********************** Start *********************************-*/
public static void main(String[] args) throws IOException
{
//----------------------- Code ---------------------------------------//
Reader in=new Reader();
Scanner sc=new Scanner(System.in);
int j=0,a=1,b=0,max=0;
String s=sc.next();
if(s.length()==2)System.out.print(2);
else
if(s.length()==1)System.out.print(1);
else
{
if(s.charAt(1)=='b')b=1;
if(s.charAt(1)=='a')j=1;
if(s.charAt(0)=='a')j++;
int dp[]=new int[s.length()];
dp[0]=1;
dp[1]=2;
for(int i=2;i<s.length();i++)
{
if(s.charAt(i)=='a')
{
j++;
dp[i]=Math.max(dp[a]+1,dp[b]+1);
a=i;
}
else
{
dp[i]=Math.max(j+1,dp[b]+1);
b=i;
}
max=Math.max(max, dp[i]);
}
System.out.print(max);
}
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 5a995609966af6a4fe86386047e0840b | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | /**
* DA-IICT
* Author : PARTH PATEL
*/
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class B877
{
public static int mod = 1000000007;
static FasterScanner in = new FasterScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
String s=in.nextLine();
if(s.length()<2)
{
out.println(s.length());
out.flush();
return;
}
int[] prefixA=new int[s.length()+1];
int[] prefixB=new int[s.length()+1];
for(int i=1;i<=s.length();i++)
{
prefixA[i]=prefixA[i-1];
prefixB[i]=prefixB[i-1];
if(s.charAt(i-1)=='a')
prefixA[i]++;
else
prefixB[i]++;
}
int maxlength=0;
for(int i=1;i<=s.length();i++)
{
for(int j=i;j<=s.length();j++)
{
int templength=prefixA[i]+prefixA[s.length()]-prefixA[j]+prefixB[j]-prefixB[i-1];
maxlength=max(maxlength, templength);
}
}
out.println(maxlength);
out.close();
}
/////////////////SEGMENT TREE (BUILD-UPDATE-QUERY)/////////////////////////////
/////////////////UPDATE FOLLOWING METHODS AS PER NEED//////////////////////////
/*
public static void buildsegmenttree(int node,int start,int end)
{
if(start==end)
{
// Leaf node will have a single element
segmenttree[node]=arr[start];
}
else
{
int mid=start+(end-start)/2;
// Recurse on the left child
buildsegmenttree(2*node, start, mid);
// Recurse on the right child
buildsegmenttree(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1];
}
}
public static void updatesegmenttree(int node,int start,int end,int idx,int val)
{
if(start==end)
{
//Leaf Node
arr[idx]+=val;
segmenttree[node]+=val;
}
else
{
int mid=start+(end-start)/2;
if(start<=idx && idx<=mid)
{
// If idx is in the left child, recurse on the left child
updatesegmenttree(2*node, start, mid, idx, val);
}
else
{
// if idx is in the right child, recurse on the right child
updatesegmenttree(2*node+1, mid+1, end, idx, val);
}
// Internal node will have the sum of both of its children
segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1];
}
}
public static long querysegmenttree(int node,int start,int end,int l,int r)
{
if(r<start || end<l)
{
// range represented by a node is completely outside the given range
return 0;
}
if(l <= start && end <= r)
{
// range represented by a node is completely inside the given range
return segmenttree[node];
}
// range represented by a node is partially inside and partially outside the given range
int mid=start+(end-start)/2;
long leftchild=querysegmenttree(2*node, start, mid, l, r);
long rightchild=querysegmenttree(2*node+1, mid+1, end, l, r);
return (leftchild+rightchild);
}
*/
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FasterScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | fe213929a515749c6f91eb51b81ac2a4 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | /**
* DA-IICT
* Author : PARTH PATEL
*/
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class B877
{
public static int mod = 1000000007;
static FasterScanner in = new FasterScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
String s=in.nextLine();
if(s.length()<2)
{
out.println(s.length());
out.flush();
return;
}
int[] prefixA=new int[s.length()+1];
if(s.charAt(0)=='a')
prefixA[1]=1;
for(int i=1;i<s.length();i++)
{
if(s.charAt(i)=='a')
prefixA[i+1]=prefixA[i-1+1]+1;
else
prefixA[i+1]=prefixA[i-1+1];
}
int[] suffixA=new int[s.length()+2];
if(s.charAt(s.length()-1)=='a')
suffixA[s.length()-1+1]=1;
for(int i=s.length()-2;i>=0;i--)
{
if(s.charAt(i)=='a')
suffixA[i+1]=suffixA[i+1+1]+1;
else
suffixA[i+1]=suffixA[i+1+1];
}
int maxlength=0;
for(int i=1;i<=s.length();i++)
{
for(int j=i+1;j<=s.length();j++)
{
int templength=prefixA[i]+suffixA[j];
//add b between i and j
int betweenA=prefixA[j]-prefixA[i-1]+suffixA[i]-suffixA[j+1];
betweenA/=2;
templength+=(j-i+1)-betweenA;
maxlength=max(maxlength, templength);
}
}
out.println(maxlength);
out.close();
}
/////////////////SEGMENT TREE (BUILD-UPDATE-QUERY)/////////////////////////////
/////////////////UPDATE FOLLOWING METHODS AS PER NEED//////////////////////////
/*
public static void buildsegmenttree(int node,int start,int end)
{
if(start==end)
{
// Leaf node will have a single element
segmenttree[node]=arr[start];
}
else
{
int mid=start+(end-start)/2;
// Recurse on the left child
buildsegmenttree(2*node, start, mid);
// Recurse on the right child
buildsegmenttree(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1];
}
}
public static void updatesegmenttree(int node,int start,int end,int idx,int val)
{
if(start==end)
{
//Leaf Node
arr[idx]+=val;
segmenttree[node]+=val;
}
else
{
int mid=start+(end-start)/2;
if(start<=idx && idx<=mid)
{
// If idx is in the left child, recurse on the left child
updatesegmenttree(2*node, start, mid, idx, val);
}
else
{
// if idx is in the right child, recurse on the right child
updatesegmenttree(2*node+1, mid+1, end, idx, val);
}
// Internal node will have the sum of both of its children
segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1];
}
}
public static long querysegmenttree(int node,int start,int end,int l,int r)
{
if(r<start || end<l)
{
// range represented by a node is completely outside the given range
return 0;
}
if(l <= start && end <= r)
{
// range represented by a node is completely inside the given range
return segmenttree[node];
}
// range represented by a node is partially inside and partially outside the given range
int mid=start+(end-start)/2;
long leftchild=querysegmenttree(2*node, start, mid, l, r);
long rightchild=querysegmenttree(2*node+1, mid+1, end, l, r);
return (leftchild+rightchild);
}
*/
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FasterScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 3de7b6c92476eb34c52bc11de1e3b50f | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.Math.*;
public class MainA
{
static int mod = (int) 1e9 + 7;
public static void main(String[] args) throws java.lang.Exception
{
InputReader in = new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
String s=in.nextLine();
int ans=0;
int len=s.length();
int cnt[]=new int[len];
if(s.charAt(0)=='a')cnt[0]=1;
for(int i=1;i<len;i++)
{
if(s.charAt(i)=='a')cnt[i]=cnt[i-1]+1;
else cnt[i]=cnt[i-1];
}
int max=0;
for(int i=0;i<=len;i++)
{
for(int j=i;j<=len;j++)
{
ans=0;
if(i!=0)ans+=cnt[i-1];
if(j!=len)
{
ans+=cnt[len-1];
if(j!=0)ans-=cnt[j-1];
}
int be=0;
if(j!=0)
{
if(i==0)
{
be=j-cnt[j-1];
}
else
{
be=(j-i)-(cnt[j-1]-cnt[i-1]);
}
}
ans+=be;
max=Math.max(ans,max);
}
}
out.println(max);
out.close();
}
public static long add(long a,long b)
{
return (a+b)%mod;
}
public static long mul(long a,long b)
{
return (a*b)%mod;
}
public static long sub(long a,long b)
{
return (a-b+mod)%mod;
}
static class Pairs implements Comparable<Pairs>
{
int x;
int y;
Pairs(int a, int b)
{
x = a;
y = b;
}
@Override
public boolean equals(Object o)
{
Pairs other=(Pairs)o;
return x==other.x && y==other.y;
}
@Override
public int compareTo(Pairs o)
{
// TODO Auto-generated method stub
return Integer.compare(x,o.x);
}
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
}
public static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
public static boolean isPal(String s)
{
for (int i = 0, j = s.length() - 1; i <= j; i++, j--)
{
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s)
{
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y)
{
if (y == 0)
return x;
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y)
{
if(y==0)
return x;
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x)
{
if (a == 0)
{
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static long max(long a, long b)
{
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b)
{
if (a > b)
return b;
else
return a;
}
public static long[][] mul(long a[][], long b[][])
{
long c[][] = new long[2][2];
c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
return c;
}
public static long[][] pow(long n[][], long p, long m)
{
long result[][] = new long[2][2];
result[0][0] = 1;
result[0][1] = 0;
result[1][0] = 0;
result[1][1] = 1;
if (p == 0)
return result;
if (p == 1)
return n;
while (p != 0)
{
if (p % 2 == 1)
result = mul(result, n);
//System.out.println(result[0][0]);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
if (result[i][j] >= m)
result[i][j] %= m;
}
}
p >>= 1;
n = mul(n, n);
// System.out.println(1+" "+n[0][0]+" "+n[0][1]+" "+n[1][0]+" "+n[1][1]);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
if (n[i][j] >= m)
n[i][j] %= m;
}
}
}
return result;
}
public static long pow(long n,long p, long m)
{
long result=1;
if(p==0)return 1;
if(p==1)return n%m;
while(p!=0)
{
if(p%2==1)result=(result*n)%m;
p >>=1;
n=(n*n)%m;
}
return result;
}
public static long pow(long n, long p)
{
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0)
{
if (p % 2 == 1)
result *= n;
p >>= 1;
n *= n;
}
return result;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 402b8a4f2202292ce93dd8c9f5b452ee | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int n=str.length();
int [] a=new int[n+1];
int [] b=new int[n+1];
int counta=0,countb=0,ans=0;
for(int i=1;i<n+1;i++)
{
if(str.charAt(i-1)=='a')
{
counta++;
a[i]=counta;
b[i]=countb;
}
else
{
countb++;
b[i]=countb;
a[i]=counta;
}
}
for(int i=0;i<n+1;i++)
{
for(int j=i;j<n+1;j++)
{
int temp=a[i]+(b[j]-b[i])+(a[n]-a[j]);
ans=Math.max(ans,temp);
}
}
System.out.print(ans);
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 1ed0927bd8dc01853116ef731f377276 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
static StringBuilder st = new StringBuilder();
static int [][] memo ;
static char [] s ;
static final int INF = (int) 1e9 ;
static int n ;
static int dp(int type , int idx)
{
if(type > 3)
return -INF;
if(idx == n)
return 0 ;
if(memo[type][idx] != -1)
return memo[type][idx] ;
int ans = 0 ;
if(type == 0 )
{
if( s[idx] == 'a')
ans = Math.max(ans, 1 + dp(1, idx + 1)) ;
}
else if(type < 3)
{
if(type == 1 && s[idx] == 'a')
ans = Math.max(ans,1 + dp(1, idx + 1)) ;
if(type == 1 && s[idx] == 'b')
ans = Math.max(ans,1 + dp(2, idx + 1)) ;
if(type == 2 && s[idx] == 'b')
ans = Math.max(ans, 1 + dp(2, idx + 1));
if(type == 2 && s[idx] == 'a')
ans = Math.max(ans, 1 + dp(3, idx + 1));
} else if(type == 3)
{
if(s[idx] == 'a')
ans = Math.max(ans, 1 + dp(3, idx + 1));
}
ans = Math.max(ans, Math.max(dp(type, idx + 1), Math.max(dp(type + 1, idx ), dp(type + 1, idx + 1)))) ;
return memo[type][idx] = ans ;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String str = sc.next();
n = str.length();
s = str.toCharArray();
memo = new int [4][n];
for(int i = 0 ; i < 4 ; i++)
Arrays.fill(memo[i], -1);
System.out.println(dp(0, 0));
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
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;
}
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 90da0f868b5f7a57758b7603590ea365 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String str = sc.next();
int n = str.length() ;
int ans = 0 ;
int [] A = new int [n+1];
int [] B = new int [n+1];
for(int i = 1 ; i <= n ; i++ )
{
if(str.charAt(i - 1) == 'a')
A[i] = 1 ;
else
B[i] = 1 ;
A[i] += A[i - 1] ;
B[i] += B[i - 1] ;
}
for(int i = 1 ; i <= n ; i ++ )
for(int j = i ; j <= n ; j++)
ans = Math.max(ans, A[i - 1] + (B[j] - B[i - 1]) + (A[n] - A[j - 1])) ;
out.println(ans);
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
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;
}
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 6cac5800c9c4615966ca62cac7c33cdc | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Vector;
public class solve {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException{
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
String str =sc.nextToken();
int n =str.length();
int a[]=new int[n];
int b[]=new int[n];
if(str.charAt(0)=='a')a[0]=1;
for(int i=1;i<n;i++){
a[i]=a[i-1];
if(str.charAt(i)=='a')
a[i]++;
}
if(str.charAt(0)=='b')b[0]=1;
for(int i=1;i<n;i++){
b[i]=b[i-1];
if(str.charAt(i)=='b')
b[i]++;
}
int max=-1;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
int ans =a[i]-a[0]+a[n-1]-a[j]+b[j]-b[i];
if(str.charAt(j)=='a' || str.charAt(0)=='a')ans++;
if(str.charAt(i)=='b')ans++;
max=Math.max(max, ans);
//System.out.println(b[3]-b[0]);
}
}
System.out.println(max);
}
}
class pair implements Comparable{
int x ,y,z;
pair(int x,int y,int z)
{
this.x=x;
this.y=y;
this.z=z;
}
@Override
public int compareTo(Object arg0) {
pair u =((pair)arg0);
return -this.z+u.z;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 82ad919146b261917bd613b2285e70e9 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
public class R442B {
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
String s = in.next();
int n = s.length();
int[] sum_b = new int[n + 1];
for (int i = 0; i < n; i++) {
sum_b[i + 1] += sum_b[i] + s.charAt(i) - 'a';
}
int ans = 0;
for (int i = 0; i <= n; i++) {
for (int j = i; j <= n; j++) {
ans = Math.max(ans, (i-sum_b[i])+(sum_b[j]-sum_b[i])+((n-j)-(sum_b[n]-sum_b[j])));
}
}
w.println(ans);
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public 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 boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | ed28066d3a29e48a4fd2427cdab2cddd | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.*;
public class Nikita_and_string
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String letters = scan.next();
int len = letters.length();
List<Integer> la = new ArrayList<>();
int laCount = 0;la.add(laCount);
List<Integer> lb = new ArrayList<>();
int lbCount = 0;lb.add(lbCount);
for(char ch : letters.toCharArray()) {
if(ch=='a') {
la.add(laCount+1);
laCount++;
lb.add(lbCount);
} else {
lb.add(lbCount+1);
lbCount++;
la.add(laCount);
}
}
int prefixA[] = new int[len+1];
int prefixB[] = new int[len+1];
if(letters.charAt(0) == 'a')
prefixA[0] = 1;
if(letters.charAt(0) == 'b')
prefixB[0] = 1;
for(int i=1; i<letters.length(); i++) {
prefixA[i] = prefixA[i-1];
if(letters.charAt(i) == 'a') {
prefixA[i]++;
}
prefixB[i] = prefixB[i-1];
if(letters.charAt(i) == 'b') {
prefixB[i]++;
}
}
int maxcount = 0, count = 0;
for(int i=0; i<la.size(); i++) {
for(int j=i; j<la.size(); j++) {
count = la.get(i) + lb.get(j) - lb.get(i) + la.get(len)-la.get(j);
maxcount = Math.max(maxcount, count);
}
}
System.out.println(maxcount);
// int maxcount = 0, count = 0;
for(int i=0; i<letters.length(); i++) {
for(int j=i; j<letters.length(); j++) {
count = prefixA[i] + prefixB[j] - prefixB[i] + prefixA[len]-prefixA[j];
maxcount = Math.max(maxcount, count);
}
}
//System.out.println(maxcount);
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 644773d635efcc6eca3452a9515a18c8 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.*;
public class Nikita_and_string
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String letters = scan.next();
int len = letters.length();
int prefixA[] = new int[len+1];
int prefixB[] = new int[len+1];
prefixA[0] = 0;
prefixB[0] = 0;
for(int i=1; i<=letters.length(); i++)
{
prefixA[i] = prefixA[i-1];
if(letters.charAt(i-1) == 'a') {
prefixA[i]++;
}
prefixB[i] = prefixB[i-1];
if(letters.charAt(i-1) == 'b') {
prefixB[i]++;
}
}
int maxcount = 0;
for(int i=0; i<=letters.length(); i++) {
for(int j=i; j<=letters.length(); j++) {
int count = prefixA[i] + prefixB[j] - prefixB[i] + prefixA[len]-prefixA[j];
maxcount = Math.max(maxcount, count);
}
}
System.out.println(maxcount);
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 52fe9e10fe0d6b84b6e54687c80b0514 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.*;
public class Nikita_and_string
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String letters = scan.next();
int len = letters.length();
List<Integer> la = new ArrayList<>();
int laCount = 0;la.add(laCount);
List<Integer> lb = new ArrayList<>();
int lbCount = 0;lb.add(lbCount);
for(char ch : letters.toCharArray()) {
if(ch=='a') {
la.add(laCount+1);
laCount++;
lb.add(lbCount);
} else {
lb.add(lbCount+1);
lbCount++;
la.add(laCount);
}
}
int prefixA[] = new int[len+1];
int prefixB[] = new int[len+1];
//if(letters.charAt(0) == 'a')
prefixA[0] = 0;
//if(letters.charAt(0) == 'b')
prefixB[0] = 0;
for(int i=1; i<=letters.length(); i++) {
prefixA[i] = prefixA[i-1];
if(letters.charAt(i-1) == 'a') {
prefixA[i]++;
}
prefixB[i] = prefixB[i-1];
if(letters.charAt(i-1) == 'b') {
prefixB[i]++;
}
}
/*
int maxcount = 0, count = 0;
for(int i=0; i<la.size(); i++) {
for(int j=i; j<la.size(); j++) {
count = la.get(i) + lb.get(j) - lb.get(i) + la.get(len)-la.get(j);
maxcount = Math.max(maxcount, count);
}
}
*/
int maxcount = 0, count = 0;
for(int i=0; i<=letters.length(); i++) {
for(int j=i; j<=letters.length(); j++) {
count = prefixA[i] + prefixB[j] - prefixB[i] + prefixA[len]-prefixA[j];
maxcount = Math.max(maxcount, count);
}
}
System.out.println(maxcount);
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | daa76997ff18e610278a46880b80ce81 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B
{
static char[] arr;
static int[][] dp;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
arr = sc.next().toCharArray();
dp = new int[4][arr.length+1];
for (int i = 0; i < dp.length; i++)
Arrays.fill(dp[i], -1);
n = arr.length;
System.out.println(solve(1,0));
pw.flush();
pw.close();
}
static int inf = (int)1e9;
static int n;
private static int solve(int state, int ind)
{
if(ind == n)
return 0;
if(dp[state][ind] != -1)
return dp[state][ind];
int ans = -inf;
if(state == 1)
{
ans = Math.max(ans, solve(2, ind));
if(arr[ind] == 'a')
{
ans = Math.max(ans, 1 + solve(1, ind+1));
}
else
{
ans = Math.max(ans, solve(1, ind+1));
}
}
else if(state == 2)
{
ans = Math.max(ans, solve(3, ind));
if(arr[ind] == 'a')
{
ans = Math.max(ans, solve(2, ind+1));
}
else
{
ans = Math.max(ans, 1 + solve(2, ind+1));
}
}
else if(state == 3)
{
if(arr[ind] == 'a')
{
ans = Math.max(ans, 1 + solve(3, ind+1));
}
else
{
ans = Math.max(ans, solve(3, ind+1));
}
}
return dp[state][ind] = 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{return Double.parseDouble(next());}
public boolean ready() throws IOException{return br.ready();}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | d0951a9b734eee16d548515868372e27 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P877B {
int [] sa, sb;
int count(int [] s, int i, int j) {
return (s[j] - s[i]);
}
public void run() throws Exception {
char [] s = next().toCharArray();
int n = s.length;
sa = new int [n + 1];
sb = new int [n + 1];
for (int i = 1; i <= n; i++) {
sa[i] = sa[i - 1] + ((s[i - 1] == 'a') ? 1 : 0);
sb[i] = sb[i - 1] + ((s[i - 1] == 'b') ? 1 : 0);
}
int m = 0;
for (int i = 0; i <= n; i++) {
for (int j = i; j <= n; j++) {
m = Math.max(m, count(sa, 0, i) + count(sb, i, j) + count(sa, j, n));
}
}
println(m);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P877B().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
} | Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 0ca533a452b13686c7bd00fec54d3c0c | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NikitaAndString {
static class Section {
boolean a;
int length;
}
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
int changes = 0;
boolean a = (s.charAt(0) == 'a');
for (int i = 1; i < s.length(); i++) {
if ((s.charAt(i) == 'a') != a) {
changes++;
a = !a;
}
}
Section[] sec = new Section[changes+1];
int count = 0;
int length = 1;
a = (s.charAt(0) == 'a');
for (int i = 1; i < s.length(); i++) {
if ((s.charAt(i) == 'a') != a) {
sec[count] = new Section();
sec[count].a = a;
sec[count].length = length;
a = !a;
length = 1;
count++;
} else {
length++;
}
}
sec[count] = new Section();
sec[count].a = a;
sec[count].length = length;
int max = 0;
for (int i = 0; i <= changes; i++) {
if (sec[i].a) { continue; }
for (int j = i; j <= changes; j++) {
if (sec[j].a) { continue; }
int bort = 0;
for (int k = i+1; k < j; k+=2) {
bort += sec[k].length;
}
for (int k = 0; k < i; k++) {
if (!sec[k].a) { bort+= sec[k].length; }
}
for (int k = j+1; k <= changes; k++) {
if (!sec[k].a) { bort+= sec[k].length; }
}
if (max < s.length() - bort) {
max = s.length() - bort;
}
}
}
if (max == 0 && s.length() > 0) { max = s.length(); }
System.out.println(max);
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | b6d90683da1321712b7811514e081029 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author phantom11
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.next();
int ans = 0, A = 0, B = 0;
int i, j;
//case for no B
int length = s.length();
for (i = 0; i < length; i++) {
if (s.charAt(i) == 'a') {
A++;
} else {
B++;
}
}
ans = Math.max(A, B);
int aBefore[] = new int[length];
int aAfter[] = new int[length];
if (s.charAt(length - 1) == 'a') {
aAfter[length - 1] = 1;
}
for (i = length - 2; i >= 0; i--) {
aAfter[i] = aAfter[i + 1];
if (s.charAt(i) == 'a') {
aAfter[i]++;
}
}
//first B
for (i = 0; i < length; i++) {
int newAns = 0;
if (s.charAt(i) == 'b') {
//find all a's before
aBefore[i] = (i == 0) ? 0 : aBefore[i - 1];
//find the last B
B = 0;
for (j = i; j < length; j++) {
if (s.charAt(j) == 'b') {
B++;
newAns = aBefore[i] + B + aAfter[j];
ans = Math.max(ans, newAns);
}
}
} else {
aBefore[i] = (i == 0) ? 1 : aBefore[i - 1] + 1;
}
}
out.printLine(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tokenizer = null;
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (IOException e) {
return null;
}
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | dfd3d1f0409b087ad7ffe553a823d8e8 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class sol {
private static int N;
private static final int A = 1;
private static final int B = 2;
private static int[] values;
private static int[] dpA;
private static int[] dpB;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
String line = f.readLine();
N = line.length();
values = new int[N];
dpA = new int[N + 1];
dpB = new int[N + 1];
for (int i = 0; i < N; i++) {
if (line.substring(i, i + 1).equals("a"))
values[i] = A;
else
values[i] = B;
}
for (int i = 1; i <= N; i++) {
dpA[i] = dpA[i - 1];
dpB[i] = dpB[i - 1];
if (values[i - 1] == A)
dpA[i]++;
else
dpB[i]++;
}
int result = 0;
for (int i = 0; i <= N; i++) {
for (int j = i; j <= N; j++) {
int count = dpA[i] + dpA[N] - dpA[j] + dpB[j] - dpB[i];
result = Math.max(result, count);
}
}
System.out.println(result);
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | 807dc32985ac7ea5e6d275037e9cec9e | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class sol {
private static int N;
private static final int A = 1;
private static final int B = 2;
private static int[] values;
private static int[] dpA;
private static int[] dpB;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
String line = f.readLine();
N = line.length();
values = new int[N];
dpA = new int[N + 1];
dpB = new int[N + 1];
for (int i = 0; i < N; i++) {
if (line.substring(i, i + 1).equals("a"))
values[i] = A;
else
values[i] = B;
}
for (int i = 1; i <= N; i++) {
dpA[i] = dpA[i - 1];
dpB[i] = dpB[i - 1];
if (values[i - 1] == A)
dpA[i]++;
else
dpB[i]++;
}
int result = 0;
for (int i = 0; i <= N; i++) {
for (int j = i; j <= N; j++) {
int count = dpA[i] + dpA[N] - dpA[j] + dpB[j] - dpB[i];
result = Math.max(result, count);
}
}
System.out.println(result);
}
public static void printArray(int[] array) {
for (int i : array)
System.out.print(i + " ");
System.out.println();
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | e4434dd007ec915474759cc3e1f29cc6 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class StringAndNikata {
public static void main(String[] args) {
String line=new Scanner(System.in).nextLine();
ArrayList<Integer> lengths=new ArrayList<Integer>();
int position=0;
dp=new int[line.length()][3];
for (int i=0; i<line.length(); i++) {
Arrays.fill(dp[i], -1);
}
int ans=go(line, 0, 0);
System.out.println(ans);
}
static int[][] dp;
public static int go(String s, int position, int state) {
if (position==s.length()) {
return 0;
}
if (dp[position][state]!=-1) {
return dp[position][state];
}
switch (state) {
case 0:
if (s.charAt(position)=='a') {
return dp[position][state]=1+go(s, position+1, 0);
}
else {
return dp[position][state]=Math.max(go(s, position+1, 0), 1+go(s, position+1, 1));
}
case 1:
if (s.charAt(position)=='a') {
return dp[position][state]=Math.max(go(s, position+1, 1), 1+go(s, position+1, 2));
}
else {
return dp[position][state]=1+go(s, position+1, 1);
}
case 2:
if (s.charAt(position)=='a') {
return dp[position][state]=1+go(s, position+1, 2);
}
else {
return dp[position][state]=go(s, position+1, 2);
}
}
return -1;
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output | |
PASSED | a44d51233cfca412eeedefa5415ebde3 | train_002.jsonl | 1508773500 | One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main3 {
static long mod = 1000000007L;
static FastScanner scanner;
public static void main(String[] args) {
scanner = new FastScanner();
String s = scanner.nextLine();
int[] afterA = new int[s.length()];
int[] beforeA = new int[s.length()];
beforeA[0] = s.charAt(0) == 'a' ? 1 : 0 ;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == 'a') beforeA[i] = beforeA[i - 1] + 1; else beforeA[i] = beforeA[i-1];
}
afterA[s.length() - 1] = s.charAt(s.length() - 1) == 'a' ? 1 : 0 ;
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == 'a') afterA[i] = afterA[i + 1] + 1; else afterA[i] = afterA[i+1];
}
int res = beforeA[s.length() - 1];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != 'b') continue;
int bcnt = 0;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) != 'b') continue;
bcnt++;
res = Math.max(res, beforeA[i] + bcnt + afterA[j]);
}
}
System.out.println(res);
}
static boolean isBeauty(List<Pos> list) {
if (list.size() <= 2) return true;
if (list.size() == 3 && list.get(0).el == 'a') return true;
return false;
}
static class Pos implements Comparable<Pos> {
int val;
char el;
public Pos(int val, char el) {
this.val = val;
this.el = el;
}
@Override
public int compareTo(Pos o) {
return Integer.compare(val, o.val);
}
}
static class Pt{
long x, y;
public Pt(long x, long y) {
this.x = x;
this.y = y;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong sum");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(long to) {
long[] result = Arrays.copyOf(FIRST_PRIMES, 10000);
int size = FIRST_PRIMES.length;
a:
for (long t = 1061; t <= to; t++) {
for (int i = 0; i < size; i++) {
if (t % result[i] == 0) {
continue a;
}
}
result[size++] = t;
}
return Arrays.copyOf(result, size);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
}
}
| Java | ["abba", "bab"] | 2 seconds | ["4", "2"] | NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful. | Java 8 | standard input | [
"dp",
"brute force"
] | c768f3e52e562ae1fd47502a60dbadfe | The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". | 1,500 | Print a single integer — the maximum possible size of beautiful string Nikita can get. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.