exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
β | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
β | difficulty
int64 -1
3.5k
β | prob_desc_output_spec
stringlengths 17
1.47k
β | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 8488ae2259ef2a6da2925562e38bc2ea | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// CODE HERE
String[] input = br.readLine().trim().split("\\s+");
final int noOfContestant = Integer.parseInt(input[0]);
final int queryPosition = Integer.parseInt(input[1]) - 1;
Integer[] numberOfSolvedProblem = new Integer[noOfContestant];
Integer[] timePenalty = new Integer[noOfContestant];
ArrayList<Integer>[] indexOfSolvedProblem = new ArrayList[55];
for (int i = 0; i < 55; i++) {
indexOfSolvedProblem[i] = new ArrayList<Integer>();
}
for (int i = 0; i < noOfContestant; i++) {
input = br.readLine().trim().split("\\s+");
numberOfSolvedProblem[i] = Integer.parseInt(input[0]);
indexOfSolvedProblem[Integer.parseInt(input[0])].add(i);
timePenalty[i] = Integer.parseInt(input[1]);
}
Collections.sort(Arrays.asList(numberOfSolvedProblem), Collections.reverseOrder());
int solvedByQueryPosition = numberOfSolvedProblem[queryPosition];
Set<Integer> uniqueTimePenalty = new HashSet<>();
ArrayList<Integer> timePenaltyOfThatSolvedProblem = new ArrayList<>();
if (indexOfSolvedProblem[solvedByQueryPosition].size() == 1){
System.out.println(1);
return;
}else {
for (int i = 0; i < indexOfSolvedProblem[solvedByQueryPosition].size(); i++) {
uniqueTimePenalty.add(timePenalty[indexOfSolvedProblem[solvedByQueryPosition].get(i)]);
timePenaltyOfThatSolvedProblem.add(timePenalty[indexOfSolvedProblem[solvedByQueryPosition].get(i)]);
}
if (uniqueTimePenalty.size() == 1){
System.out.println(indexOfSolvedProblem[solvedByQueryPosition].size());
return;
}
Collections.sort(timePenaltyOfThatSolvedProblem);
int temp = 0;
for (int i = 0; i < queryPosition; i++) {
if (numberOfSolvedProblem[i] == solvedByQueryPosition){
++temp;
}
}
int timePenaltyAtQueryPosition = timePenaltyOfThatSolvedProblem.get(temp);
temp = 0;
for (int i = 0; i < timePenaltyOfThatSolvedProblem.size(); i++) {
if (timePenaltyAtQueryPosition == timePenaltyOfThatSolvedProblem.get(i)){
++temp;
}
}
System.out.println(temp);
}
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | f8adf763a17553899041790fd09a153f | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
public class RankList {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
helper();
}
public static void helper() {
int n = (int)input();
int k = (int)input();
int[][] arr = new int[n][2];
for (int i = 0; i < n; i++) {
arr[i][0] = (int)input();
arr[i][1] = (int)input();
}
Arrays.sort(arr, (a, b) -> (a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]));
int[] pair = arr[k - 1];
int idx1 = k - 1, idx2 = k - 1;
while (idx1 >= 0 && arr[idx1][0] == pair[0] && arr[idx1][1] == pair[1]) idx1--;
idx1++;
while (idx2 < n && arr[idx2][0] == pair[0] && arr[idx2][1] == pair[1]) idx2++;
idx2--;
print(idx2 - idx1 + 1);
}
public static long input() {
return scn.nextLong();
}
public static String input(int... var) {
return scn.next();
}
public static void TakeInput(int[] arr) {
for (int i = 0; i < arr.length; i++)
arr[i] = (int)input();
}
public static void TakeInput(long[] arr) {
for (int i = 0; i < arr.length; i++)
arr[i] = input();
}
public static void printArray(int[] arr) {
for (int val : arr)
print(val + " ");
print("\n");
}
public static void printArray(long[] arr) {
for (long val : arr)
print(val + " ");
print("\n");
}
public static <T> void print(T t) {
System.out.print(t);
}
public static void print() {
System.out.println();
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | b270149495f1d246ac821b39ee42668f | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException{
FastScanner fs = new FastScanner();
int n = fs.nextInt();
int k = fs.nextInt();
int[] a = new int[n];
HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();
for(int i=0 ; i<n ; i++) {
a[i] = fs.nextInt();
int time = fs.nextInt();
if(map.containsKey(a[i])) {
map.get(a[i]).add(time);
}else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(time);
map.put(a[i], temp);
}
}
sort(a);
int ind = 0;
int there = a[k-1];
ArrayList<Integer> x = map.get(there);
for(int i=0 ; i<n ; i++) {
if(a[i]==there) {
ind = i;
break;
}
}
Collections.sort(x);
int t = x.get(k-ind-1);
int c = 0;
for(int e:x) {
if(e==t) c++;
}
System.out.println(c);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[a.length-i-1]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 1174b347ea70300675da634cc61aeed8 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF166A extends PrintWriter {
CF166A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF166A o = new CF166A(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++) {
int p = sc.nextInt();
int t = sc.nextInt();
aa[i] = p * 50 + 50 - t;
}
Arrays.sort(aa);
int a = aa[n - k];
int ans = 0;
for (int i = 0; i < n; i++)
if (aa[i] == a)
ans++;
println(ans);
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 6cd4844ae2d40fb8ca13ff5406f1a34c | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
/**
* @author AnonymousP
* @__WHEN YOU FEEL LIKE QUITTING, THINK ABOUT WHY YOU STARTED__@
*/
//COMBINATON = nCr = n*(n-1)/2
public class Rank_list {
public static void main(String[] args) {
int t = sc.nextInt();
int c = sc.nextInt() - 1;
ArrayList<Pair> al = new ArrayList<>();
while (t-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
al.add(new Pair(a, b));
}
Collections.sort(al);
Collections.sort(al, Pair.byA);
// Collections.sort(al, Pair.byB);
int nowA = al.get(c).getFirstElem();
int nowB = al.get(c).getSecElem();
//Dbug
/* int j = 1;
for (int i = 0; i < al.size(); i++) {
prln(j + " " + al.get(i));
j++;
}*/
int count = 0;
for (Pair p : al) {
if (p.getFirstElem() == nowA && p.getSecElem() == nowB) {
count++;
}
}
prln(count);
close();
}
static FastReader sc = new FastReader();
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
static void shuffleIntArray(int[] arr) {
int n = arr.length;
Random rnd = new Random();
Pair p = new Pair();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
//************************************************************************//
//PAIR CLASS
//************************************************************************//
static class Pair implements Comparable<Pair> {
int a, b;
Pair() {
}
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int getFirstElem() {
return a;
}
public int getSecElem() {
return b;
}
//Sort Both A and B Choto theke boro//
@Override
public int compareTo(Pair o) {
if (a == o.a) return Integer.compare(b, o.b);
return Integer.compare(a, o.a);
}
public static Comparator<Pair> byA = (Pair t, Pair t1) -> {
return Integer.compare(t1.a, t.a);
};
public static Comparator<Pair> byB = (Pair t, Pair t1) -> {
return Integer.compare(t1.b, t.b);
};
public String toString() {
return "{" + a + ", " + b + "}";
}
}
//************************************************************************//
//************************************************************************//
//CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_CLASS_//
//*******FAST IO*************FAST IO***************FAST IO****************//
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// output
static void pr(int i) {
__out.print(i);
}
static void prln(int i) {
__out.println(i);
}
static void pr(long l) {
__out.print(l);
}
static void prln(long l) {
__out.println(l);
}
static void pr(double d) {
__out.print(d);
}
static void prln(double d) {
__out.println(d);
}
static void pr(char c) {
__out.print(c);
}
static void prln(char c) {
__out.println(c);
}
static void pr(char[] s) {
__out.print(new String(s));
}
static void prln(char[] s) {
__out.println(new String(s));
}
static void pr(String s) {
__out.print(s);
}
static void prln(String s) {
__out.println(s);
}
static void pr(Object o) {
__out.print(o);
}
static void prln(Object o) {
__out.println(o);
}
static void prln() {
__out.println();
}
static void pryes() {
__out.println("yes");
}
static void pry() {
__out.println("Yes");
}
static void prY() {
__out.println("YES");
}
static void prno() {
__out.println("no");
}
static void prn() {
__out.println("No");
}
static void prN() {
__out.println("NO");
}
static void pryesno(boolean b) {
__out.println(b ? "yes" : "no");
}
;
static void pryn(boolean b) {
__out.println(b ? "Yes" : "No");
}
static void prYN(boolean b) {
__out.println(b ? "YES" : "NO");
}
static void prln(int... a) {
for (int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i) ;
__out.println(a[a.length - 1]);
}
static void prln(long... a) {
for (int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i) ;
__out.println(a[a.length - 1]);
}
static <T> void prln(Collection<T> c) {
int n = c.size() - 1;
Iterator<T> iter = c.iterator();
for (int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i) ;
if (n >= 0) {
__out.println(iter.next());
} else {
__out.println();
}
}
static void h() {
__out.println("hlfd");
flush();
}
static void flush() {
__out.flush();
}
static void close() {
__out.close();
}
//*******FAST IO*************FAST IO***************FAST IO****************//
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | f082bcc525b8e7260405827c3b42d6ac | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
import java.io.*;
public class Rank_List {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader t = new FastReader();
PrintWriter o = new PrintWriter(System.out);
int n = t.nextInt();
int rank = t.nextInt();
Pair[] a = new Pair[n];
for (int i = 0; i < n; ++i) {
int x = t.nextInt();
int y = t.nextInt();
a[i] = new Pair(x, y);
}
ompare ob = new ompare();
ob.compare(a, n);
int x = a[rank - 1].x;
int y = a[rank - 1].y;
int count = 0;
for (int i = 0; i < n; ++i) {
if (a[i].x == x && a[i].y == y)
count++;
}
o.println(count);
o.flush();
o.close();
}
}
class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class ompare {
void compare(Pair arr[], int n) {
Arrays.sort(arr, new Comparator<Pair>() {
@Override
public int compare(Pair p1, Pair p2) {
if (p2.x != p1.x)
return p2.x - p1.x;
else
return p1.y - p2.y;
}
});
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 78d321437ad1ed483dcc28f77c625aeb | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
public class rankLIst
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
int n=s1.nextInt();
int k=s1.nextInt();
s1.nextLine();
int[] p=new int[n];
int[] t=new int[n];
for(int i=0;i<n;i++)
{
p[i]=s1.nextInt();
t[i]=s1.nextInt();
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(p[j]>p[i])
{
int temp1=p[i];
p[i]=p[j];
p[j]=temp1;
int temp2=t[i];
t[i]=t[j];
t[j]=temp2;
}
if(p[i]==p[j] && t[i]>t[j])
{
int temp1=t[i];
t[i]=t[j];
t[j]=temp1;
}
}
}
int c=p[k-1];
int d=t[k-1];
int ans=0;
for(int i=0;i<n;i++)
{
if(p[i]==c && t[i]==d)
ans+=1;
}
if (ans==0)
ans=1;
System.out.println(ans);
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | e764957e666e1227230d3d82a77520fc | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
public class rankLIst
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
int n=s1.nextInt();
int k=s1.nextInt();
s1.nextLine();
int[] p=new int[n];
int[] t=new int[n];
for(int i=0;i<n;i++)
{
p[i]=s1.nextInt();
t[i]=s1.nextInt();
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(p[j]>p[i])
{
int temp1=p[i];
p[i]=p[j];
p[j]=temp1;
int temp2=t[i];
t[i]=t[j];
t[j]=temp2;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(p[i]==p[j] && t[i]>t[j])
{
int temp1=t[i];
t[i]=t[j];
t[j]=temp1;
}
}
}
int c=p[k-1];
int d=t[k-1];
int ans=0;
for(int i=0;i<n;i++)
{
if(p[i]==c && t[i]==d)
ans+=1;
}
//System.out.println();
if (ans==0)
ans=1;
System.out.println(ans);
//System.out.println();
//for(int i=0;i<n;i++)
// System.out.println(p[i]+" "+t[i]);
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 12c16a4d982157cc3c4cc5b8e3852f0d | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
Integer [][] arr=new Integer[n][2];
for(int i=0;i<n;i++){
for(int j=0;j<2;j++){
arr[i][j]=sc.nextInt();
}
}
final Comparator<Integer[]> arrayComparator = new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
if(o1[0]==o2[0]) return o1[1].compareTo(o2[1]);
else return o2[0].compareTo(o1[0]);
}
};
Arrays.sort(arr, arrayComparator);
for(int i=0;i<n;i++){
for(int j=0;j<2;j++){
// System.out.print(arr[i][j]+"aa ");
}
//System.out.println("");
}
int num1=arr[k-1][0];
//System.out.println(num1+"aa");
int num2=arr[k-1][1];
//System.out.println(num2+"aa");
int res=0;
for(int i=0;i<n;i++){
if(num1==arr[i][0]){
if(num2==arr[i][1]){
res++;
}
}
}
System.out.print(res);
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 4c68f0b1f3d567d85122b284f1f0ba2c | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
public class RankList {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
k=k-1;
int [][] arr=new int[n][2];
for(int i=0;i<n;i++) {
arr[i][0]=in.nextInt();
arr[i][1]=in.nextInt();
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[0] < entry2[0])
return 1;
else if(entry1[0] > entry2[0])
return -1;
else if(entry1[0]==entry2[0]&&entry1[1]<entry2[1])
return -1;
else if(entry1[0]==entry2[0]&&entry1[1]>entry2[1])
return 1;
else
return 0;
}
}); // End of function call sort().
/*for(int i=0;i<n;i++) {
System.out.print(arr[i][0]);
System.out.print(" ");
System.out.println(arr[i][1]);
}*/
int count=0;
int a=arr[k][0];
int b=arr[k][1];
for(int i=k;i<n;i++) {
if(arr[i][0]==a&&arr[i][1]==b)count++;
else break;
}
for(int i=k;i>=0;i--) {
if(arr[i][0]==a&&arr[i][1]==b)count++;
else break;
}
System.out.println(count-1);
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 43488df3bfe2730a2fd6ecbe988a95e7 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.*;
import java.util.Arrays;
public class RankList {
static class Team implements Comparable<Team>
{
int problemsSolved;
int penaltyTime;
public Team(int x, int y)
{
this.problemsSolved = x;
this.penaltyTime = y;
}
// descending order
public int compareTo(Team otherTeam)
{
if (this.problemsSolved < otherTeam.problemsSolved)
{
return 1;
}
else if (this.problemsSolved > otherTeam.problemsSolved)
{
return -1;
}
else
{
return this.penaltyTime - otherTeam.penaltyTime;
}
}
}
static BufferedReader reader = new BufferedReader(new InputStreamReader (System.in));
public static void main (String [] args) throws IOException {
int [] nk = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int n = nk[0];
int k = nk[1];
Team [] teams = new Team[n];
int index = 0;
while (index < n)
{
int [] team = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
teams[index] = new Team(team[0], team[1]);
index++;
}
Arrays.sort(teams);
int currentSame = 0;
for (int i = 0; i < n; i++)
{
if (i == 0)
currentSame = 1;
else if (teams[i].problemsSolved == teams[i-1].problemsSolved &&
teams[i].penaltyTime == teams[i-1].penaltyTime)
currentSame++;
else
currentSame = 1;
if (i == k - 1)
{
index = i + 1;
while (index < n &&
teams[index].problemsSolved == teams[index-1].problemsSolved &&
teams[index].penaltyTime == teams[index-1].penaltyTime)
{
currentSame++;
index++;
}
System.out.println(currentSame);
return;
}
}
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 2f8469e46d0c5a9a853a084004c57db8 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static class Team implements Comparable<Team> {
int p;
int t;
Team(int p, int t) {
this.p = p;
this.t = t;
}
@Override
public int compareTo(Team team) {
if (p < team.p || (p == team.p && t > team.t))
return 1;
else if (p == team.p && t == team.t)
return 0;
return -1;
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Team[] teams = new Team[n];
for (int i = 0; i < n; i++) {
int p = in.nextInt();
int t = in.nextInt();
teams[i] = new Team(p, t);
}
Arrays.sort(teams);
int pos = k - 1;
int res = 1;
while (pos > 0 && teams[pos - 1].compareTo(teams[pos]) == 0) {
pos--;
res++;
}
pos = k - 1;
while (pos < n - 1 && teams[pos + 1].compareTo(teams[pos]) == 0) {
pos++;
res++;
}
out.println(res);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 8c04c9b520baabcb6d4bef39cc710256 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class A {
public static void main(String[] agrs) {
FastScanner sc = new FastScanner();
// int n = sc.nextInt();
// while(n-->0) {
//
// }
int n = sc.nextInt();
int k = sc.nextInt();
List<Team> list = new ArrayList<>();
Map<String,Integer> map = new HashMap<>();
for(int i = 0; i < n; i++) {
list.add(new Team(sc.nextInt(),sc.nextInt()));
map.put(list.get(i).solved+""+list.get(i).penalty,
map.getOrDefault(list.get(i).solved+""+list.get(i).penalty, 0) + 1);
}
Collections.sort(list, (a,b) -> (b.solved-a.solved == 0) ?
(a.penalty - b.penalty) :
(b.solved-a.solved));
String team = list.get(k-1).solved+""+list.get(k-1).penalty;
System.out.println(map.get(team));
}
static class Team{
int solved;
int penalty;
public Team(int solved, int penalty) {
this.solved = solved;
this.penalty = penalty;
}
}
static int gcd(int a, int b) {
return a%b == 0 ? b : gcd(b,a%b);
}
static int mod = 1000000007;
static long pow(int a, int b) {
if(b == 0) {
return 1;
}
if(b == 1) {
return a;
}
if(b%2 == 0) {
long ans = pow(a,b/2);
return ans*ans;
}
else {
long ans = pow(a,(b-1)/2);
return a * ans * ans;
}
}
static boolean[] sieve(int n) {
boolean isPrime[] = new boolean[n+1];
for(int i = 2; i <= n; i++) {
if(isPrime[i]) continue;
for(int j = 2*i; j <= n; j+=i) {
isPrime[j] = true;
}
}
return isPrime;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | b4a5ec42bc064e65374a38b1415715d6 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author grolegor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
List<Team> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int p = in.nextInt();
int d = in.nextInt();
list.add(new Team(p, d));
}
list.sort(Comparator.comparing(Team::getP, Comparator.reverseOrder()).thenComparing(Team::getT));
Team t = list.get(k - 1);
int ans = 0;
for (int i = 0; i < n; i++) {
Team curr = list.get(i);
if (curr.getP() == t.getP() && curr.getT() == t.getT()) {
ans++;
}
}
out.println(ans);
}
}
static class Team {
private int p;
private int t;
public int getP() {
return p;
}
public int getT() {
return t;
}
public Team(int p, int t) {
this.p = p;
this.t = t;
}
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 5b01da77afcd4f45b3a8c0f7781f2fbe | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.*;
import java.util.*;
public class p166A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
Team[] teamList = new Team[n];
for(int i = 0; i < n; i++){
st = new StringTokenizer(br.readLine());
teamList[i] = new Team(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
Arrays.sort(teamList);
int problems = teamList[k - 1].getNumProblemsSolved();
int index = 0;
int j = index;
while(teamList[index].getNumProblemsSolved() != problems){
index++;
}
j = index;
ArrayList<Team> list = new ArrayList<>();
while(j < teamList.length && teamList[j].getNumProblemsSolved() == problems){
list.add(teamList[j]);
j++;
}
Collections.sort(list, new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return o1.getPenaltyTime() - o2.getPenaltyTime();
}
});
int l = 0;
for(int i = index; i < j; i++){
teamList[i] = list.get(l++);
}
int time = teamList[k - 1].getPenaltyTime();
int numTeams = 1;
for(int i = 0; i < teamList.length; i++){
if(teamList[i].getNumProblemsSolved() == problems && teamList[i].getPenaltyTime() == time && i != k - 1){
numTeams++;
} else if(teamList[i].getNumProblemsSolved() < problems)
break;
}
pw.println(numTeams);
pw.close();
}
}
class Team implements Comparable<Team>{
private int numProblemsSolved, penaltyTime;
public Team(int numProblemsSolved, int penaltyTime){
this.numProblemsSolved = numProblemsSolved;
this.penaltyTime = penaltyTime;
}
public int getNumProblemsSolved() {
return numProblemsSolved;
}
public int getPenaltyTime() {
return penaltyTime;
}
@Override
public String toString() {
return getNumProblemsSolved() + " " + getPenaltyTime();
}
@Override
public int compareTo(Team o) {
return o.getNumProblemsSolved() - getNumProblemsSolved();
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 394372db5eedd7c5a5ebd0c8e3afbddb | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
// warm-up
public class RankList {
static Set<Team> s = new HashSet<Team>();
static class Team implements Comparable<Team>{
int p, t; // Problems solved, penalty time
Team (int a, int b) {
p=a; t=b;
}
public int compareTo (Team other) {
return p==other.p ? t-other.t : other.p-p;
}
@Override
public boolean equals (Object other) {
Team o = (Team) other;
return p==o.p && t==o.t;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + this.p+this.t;
return hash;
}
public String toString () {
return p+" : "+t;
}
}
static void solve() {
Scanner sc = new Scanner(System.in);
int noc=sc.nextInt(), k=sc.nextInt(), i=0, n=0, j=1;
Team[] t = new Team[noc];
while (noc-->0) t[i++] = new Team (sc.nextInt(), sc.nextInt());
Arrays.sort(t);
Team b = t[k-1];
for (Team a : t) if (a.equals(b)) n++;
System.out.println(n);
sc.close();
}
public static void main(String args[]) {
solve();
}
}
| Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | 465032d5b20627e93326a8d191c2bf40 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
static Scanner scr=new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
// int t=scr.nextInt();
// while(t-->0) {
solve();
System.out.println();
// }
}
static void solve() {
int n=scr.nextInt();
int k=scr.nextInt();
ArrayList<pair>a=new ArrayList<pair>();
for(int i=0;i<n;i++) {
int p=scr.nextInt();
int t=scr.nextInt();
a.add(new pair(p,t));
}
Collections.sort(a,new Comparator<pair>() {
public int compare(pair a,pair b) {
if(b.p>a.p) {
return 1;
}else if(a.p==b.p && a.t>b.t ) {
return 1;
}else if(b.p<a.p) {
return -1;
}
return -1;
}
});
int count=0;
for(int i=0;i<n;i++) {
if(a.get(i).p==a.get(k-1).p && a.get(i).t==a.get(k-1).t) {
count++;
}
}
System.out.print(count);
}
}
class pair{
int p;;
int t;
pair(int p,int t){
this.p=p;
this.t=t;
}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | eda32c496f7659d9490d62f7a313aa19 | train_001.jsonl | 1332516600 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either paβ>βpb, or paβ=βpb and taβ<βtb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places yβ+β1, yβ+β2, ..., yβ+βx. The teams that performed worse than the teams from this group, get their places in the results table starting from the yβ+βxβ+β1-th place.Your task is to count what number of teams from the given list shared the k-th place. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class ladders166a {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
read();
int n = nextInt(), k = nextInt(), s[][] = new int[n][3];
for(int i = 0; i < n; ++i) {
read();
s[i] = new int[] {i, nextInt(), nextInt()};
}
sort(s, (a, b) -> a[1] == b[1] ? a[2] == b[2] ? a[0] - b[0] : a[2] - b[2] : b[1] - a[1]);
int cnt = 1, j = k - 1;
while(j > 0 && s[j][1] == s[j - 1][1] && s[j][2] == s[j - 1][2]) {
++cnt;
--j;
}
j = k - 1;
while(j < n - 1 && s[j][1] == s[j + 1][1] && s[j][2] == s[j + 1][2]) {
++cnt;
++j;
}
println(cnt);
close();
}
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static void read() throws IOException {input = new StringTokenizer(__in.readLine());}
static String readLine() throws IOException {return __in.readLine();}
static int nextInt() {return Integer.parseInt(input.nextToken());}
static int readInt() throws IOException {return Integer.parseInt(__in.readLine());}
static void print(Object o) {__out.print(o);}
static void println(Object o) {__out.println(o);}
static void printyn(boolean b) {__out.println(b ? "YES" : "NO");}
static void println(int[] a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
static void println() {__out.println();}
static void close() {__out.close();}
} | Java | ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"] | 2 seconds | ["3", "4"] | NoteThe final results' table for the first sample is: 1-3 places β 4 solved problems, the penalty time equals 10 4 place β 3 solved problems, the penalty time equals 20 5-6 places β 2 solved problems, the penalty time equals 1 7 place β 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β 5 solved problems, the penalty time equals 3 2-5 places β 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | Java 11 | standard input | [
"sortings",
"binary search",
"implementation"
] | 63e03361531999db408dc0d02de93579 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1ββ€βpi,βtiββ€β50) β the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. | 1,100 | In the only line print the sought number of teams that got the k-th place in the final results' table. | standard output | |
PASSED | c2e0f11508ca5fe4a6368b1ebf6f7361 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author dy
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; ++i) arr[i] = in.nextInt();
//int reversePair = binary(arr, 0, arr.length);
int reversePair = brute(arr, 0, arr.length);
int ans = reversePair / 2 * 4;
if (reversePair % 2 == 1) ans += 1;
out.println(ans);
}
private int brute(int[] arr, int from, int to) {
int ans = 0;
for (int i = from; i < to; ++i)
for (int j = from; j < i; ++j) ans += arr[i] < arr[j] ? 1 : 0;
return ans;
}
int tmp[] = new int[3000 + 10];
private int binary(int[] arr, int from, int to) {
if (from + 1 >= to)
return 0;
int mid = from + (to - from) / 2;
int l = binary(arr, from, mid);
int r = binary(arr, mid, to);
int ans = l + r;
int i,j, idx;
for (i = from, j = mid, idx = from; i < mid && j < to;) {
if (arr[i] > arr[j]) {
ans += to - j;
tmp[idx++] = arr[i++];
} else {
tmp[idx++] = arr[j++];
}
}
for (;i < mid; ++i) tmp[idx++] = arr[i++];
for (;j < to; ++j) tmp[idx++] = arr[j++];
for (i = from; i < to; ++i) arr[i] = tmp[i];
return ans;
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 0f060f48f5e5a06e36a9055e2091e335 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
TreeSet<Integer> tree = new TreeSet<Integer>();
int count = 0;
for (int i = 0; i < n; i++) {
count += tree.tailSet(arr[i]).size();
tree.add(arr[i]);
}
if (count % 2 == 0) {
System.out.println(count * 2);
} else {
System.out.println((count - 1) * 2 + 1);
}
}
} | Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 6ee78af8c34bcf5e01d731a08463ac66 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | // @author Sanzhar
import java.io.*;
import java.util.*;
import java.awt.Point;
public class Template {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
public void run() throws Exception {
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
in.close();
}
public void solve() throws Exception {
int n = nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = nextInt();
}
int k = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (p[j] > p[i]) {
k++;
}
}
}
if (k % 2 == 1) {
out.println(2 * k - 1);
} else {
out.println(2 * k);
}
}
public static void main(String[] args) throws Exception {
new Template().run();
}
} | Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | cf5b86c605da7d52c85852f6c00ae64f | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
String line = scan.nextLine().trim();
String[] tmp = line.split(" ");
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = Integer.valueOf(tmp[i]);
}
int c = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if (p[i] > p[j]) c++;
}
if (c == 0) System.out.println(0);
else {
int ret = 0;
while (c > 1) {
ret += 4;
c -= 2;
}
if (c == 1) ret += 1;
System.out.println(ret);
}
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | e5d3414001da9288b61644c68bf6d4b4 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int[]p = new int[n+1];
for (int i = 1; i <= n; i++) {
p[i] = nextInt();
}
int inv = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < i; j++) {
if (p[j] > p[i])
inv++;
}
}
if (inv==0) {
System.out.println(0);
return;
}
int[]ans = new int[inv+1];
ans[1] = 1;
for (int i = 2; i <= inv; i++) {
ans[i] = ans[i-2]+4;
}
System.out.println(ans[inv]);
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 6b313204f501efe72677855028d53898 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author balbasaur
*/
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[] a = new int[n];
for (int i = 0;i < n; ++i)
a[i] = in.nextInt();
int cnt = 0 ;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (a[i] > a[j])cnt++;
int ans = cnt*2;
if (cnt % 2 == 1)
ans--;
out.print(ans);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 6ee30c888f2771e18964ca3934df42d4 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class CF_D {
public static void main(String[] args) throws Exception {
new CF_D();
}
CF_D() throws Exception {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int curr = 0;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) {
curr++;
}
}
}
int res = 0;
while (curr > 1) {
res += 4;
curr -= 2;
}
res += (curr & 1);
out.printf("%.9f\n", (double) res);
out.close();
}
public class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 608794c000c9dd3439d89084e97402ed | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
final int MAXN = 3001;
int[] p = new int[MAXN];
int n;
int[] ans = new int[MAXN * MAXN];
private void solve() throws IOException {
n = nextInt();
for(int i = 0; i < n; i++)
p[i] = nextInt();
int I = 0;
for(int i = 0; i < n; i++)
for(int j = i+1; j < n; j++)
if(p[i] > p[j])
I++;
ans[0] = 0;
ans[1] = 1;
for(int i = 2; i <= I; i++)
ans[i] = 4 + ans[i-2];
out.printf(Locale.US,"%.6f",(double)ans[I]);
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 1c174e0d60395a4791693b6c5a683102 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.StringTokenizer;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
public Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
public int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
public char[][] nextGrid(int r)
{
char[][] grid = new char[r][];
for(int i = 0; i < r; i++)
grid[i] = next().toCharArray();
return grid;
}
public static <T> T fill(T arreglo, int val)
{
if(arreglo instanceof Object[])
{
Object[] a = (Object[]) arreglo;
for(Object x : a)
fill(x, val);
}
else if(arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if(arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if(arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
<T> T[] nextObjectArray(Class <T> clazz, int size)
{
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
for(int c = 0; c < 3; c++)
{
Constructor <T> constructor;
try
{
if(c == 0)
constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE);
else if(c == 1)
constructor = clazz.getDeclaredConstructor(Scanner.class);
else
constructor = clazz.getDeclaredConstructor();
}
catch(Exception e)
{
continue;
}
try
{
for(int i = 0; i < result.length; i++)
{
if(c == 0)
result[i] = constructor.newInstance(this, i);
else if(c == 1)
result[i] = constructor.newInstance(this);
else
result[i] = constructor.newInstance();
}
}
catch(Exception e)
{
throw new RuntimeException(e);
}
return result;
}
throw new RuntimeException("Constructor not found");
}
public void printLine(int... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(long... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(int prec, double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.printf("%." + prec + "f", vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.printf(" %." + prec + "f", vals[i]);
System.out.println();
}
}
public Collection <Integer> wrap(int[] as)
{
ArrayList <Integer> ans = new ArrayList <Integer> ();
for(int i : as)
ans.add(i);
return ans;
}
public int[] unwrap(Collection <Integer> collection)
{
int[] vals = new int[collection.size()];
int index = 0;
for(int i : collection) vals[index++] = i;
return vals;
}
}
static int dp(int n)
{
if(n == 0) return 0;
if(n == 1) return 3;
return 4 + dp(n - 2);
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
int n = sc.nextInt();
int[] vals = sc.nextIntArray(n);
int cuenta = 0;
for(int i = 0; i < n; i++)
{
final int este = vals[i];
for(int j = 0; j < i; j++)
{
if(vals[j] > este)
cuenta++;
}
}
if(cuenta != 0)
cuenta = dp(cuenta - 1) + 1;
System.out.println(cuenta);
}
} | Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | ab675f4be51ae3b258a36d4aa6cbfb6b | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws Exception {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(input);
int N = Integer.parseInt(read.readLine());
StringTokenizer token = new StringTokenizer(read.readLine());
int P[] = new int[N];
for (int i = 0; i < N; ++i) {
P[i] = Integer.parseInt(token.nextToken());
}
int inv = 0;
for (int i = 1; i < N; ++i) {
int j = i;
while (j > 0 && P[j-1] > P[j]) {
int tmp = P[j-1];
P[j-1] = P[j];
P[j] = tmp;
j--;
inv++;
}
}
int ret = 4 * (inv/2) + (inv % 2);
System.out.println("" + ret);
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 1bdc7466e273e607777a241e3d96c1e9 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | //package com.javarush.test.eoly.spbsu1.force204;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* User: Π²
* Date: 08.10.13
* Time: 9:23
* To change this template use File | Settings | File Templates.
*/
public class D204
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] ar = new int[n*n];
int[] ar2 = new int[n*n];
for (int i = 0; i < n; i++){
ar[i] = sc.nextInt();
}
int ans = 0;
int swap;
for (int i = 0; i < n; i++){
for (int j = 0; j < n-1; j++){
if (ar[j] > ar[j+1]){
ans++;
swap = ar[j];
ar[j] = ar[j+1];
ar[j + 1] = swap;
}
}
}
//System.out.println(ans);
ar2[0] = 0;
ar2[1] = 1;
for (int i = 2; i <= ans; i++){
ar2[i] = 4 + ar2[i-2];
}
System.out.println(ar2[ans]);
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 432ee59249096550816dc1cd4570c04f | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ar[] = new int[n];
for(int i = 0; i < n; i++)
ar[i] = sc.nextInt();
int ans = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(ar[i] > ar[j])
ans++;
}
}
if(ans == 0){
System.out.println(0);
}else if((ans & 1) == 0){
System.out.println(ans * 2);
}else{
System.out.println((ans - 1) * 2 + 1);
}
sc.close();
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 3b5fd8e1bde4fc0a63dce9c4cf0c1410 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) {
solve(new InputReader(System.in));
}
static void solve(InputReader in) {
int n = in.ni();
int[] arr = in.na(n);
int inv = 0;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (arr[j] > arr[i]) {
inv++;
}
}
}
if (inv == 0) {
System.out.println(0);
return;
}
int pre = 0, cur = 1;
for (int i = 1; i < inv; i++) {
int tmp = cur;
cur = 4 + pre;
pre = tmp;
}
System.out.println(cur);
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
int[] na(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | c336b8f44bfca551b107faf8b4c8f0bb | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n = sc.nextInt();
int[] a = sc.nextIntArray(n);
int f = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i < j && a[i] > a[j]) ++f;
}
}
double ans = 0;
for (int i = 0; i < f; i++) {
if (i % 2 == 0) ans += 1;
else ans += 3;
}
out.printf("%.8f\n",ans);
}
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
static void tr(Object... os) {
System.err.println(deepToString(os));
}
static void fill(int[][] a, int val) {
for(int i = 0; i < a.length; i++) Arrays.fill(a[i], val);
}
static void fill(int[][][] a, int val) {
for(int i = 0; i < a.length; i++) fill(a[i], val);
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
| Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 2e36ba14ec876e65263e95cdea716c64 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.util.*;
/**
* @author Assassin
*/
public class D {
private BufferedReader reader;
private PrintWriter out;
private StringTokenizer tokenizer;
//private final String filename = "filename";
private void init(InputStream input, OutputStream output) throws IOException {
reader = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output)));
//reader = new BufferedReader(new FileReader(filename + ".in"));
//out = new PrintWriter(new FileWriter(filename + ".out"));
tokenizer = new StringTokenizer("");
}
private String nextLine() throws IOException {
return reader.readLine();
}
private String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private void run() throws IOException {
init(System.in, System.out);
int n = nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = nextInt();
}
int c, s = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (p[j] > p[j + 1]) {
c = p[j];
p[j] = p[j + 1];
p[j + 1] = c;
s++;
}
}
}
int a = 1;
int k = 1;
if (s == 0) {
k -= 2;
}
if (s == 1) {
out.println("1");
} else {
while (s != 0) {
if (a % 4 == 0) {
s++;
} else {
s--;
}
k++;
a++;
}
k++;
out.println(k);
}
out.close();
System.exit(0);
}
public static void main(String[] args) throws IOException {
new D().run();
}
} | Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | 22c33c125eda6a3fdcc972cc358bbfd8 | train_001.jsonl | 1380900600 | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and iβ+β1, for which an inequality piβ>βpiβ+β1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and iβ+β1, for which the inequality piβ<βpiβ+β1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
final int inf = Integer.MAX_VALUE / 2;
int rd() throws IOException {
return Integer.parseInt(nextToken());
}
int[] a = new int[100001];
Node[] ans = new Node[100001];
class Node {
int v = 0;
int ind = 0;
}
int start, finish;
void solve() throws IOException {
int n = rd();
for (int i = 0; i < n; i ++){
a[i] = rd();
}
int inv = 0;
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j ++){
if (a[i] > a[j]) inv++;
}
}
if (inv % 2 == 0){
inv = inv * 2;
} else {
inv = (inv - 1) * 2 + 1;
}
out.print(inv);
}
void run() {
try {
//in = new BufferedReader(new FileReader("cycle.in"));
//out = new PrintWriter("cycle.out");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Locale.setDefault(Locale.UK);
solve();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
out.close();
}
}
public static void main(String Args[]) {
new Solution().run();
}
} | Java | ["2\n1 2", "5\n3 5 2 4 1"] | 1 second | ["0.000000", "13.000000"] | NoteIn the first test the sequence is already sorted, so the answer is 0. | Java 7 | standard input | [
"math"
] | c4609bd2b4652cb5c2482b16909ec64a | The first line contains integer n (1ββ€βnββ€β3000). The next line contains n distinct integers p1, p2, ..., pn (1ββ€βpiββ€βn) β the permutation p. The numbers are separated by spaces. | 1,900 | In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6. | standard output | |
PASSED | c442eb4eb1928c8c863f9b9cb47c92f8 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.util.*;
public class ProblemD {
public static void main(String[] args) {
@SuppressWarnings({ "unused", "resource" })
Scanner sc = new Scanner(System.in);
int N=sc.nextInt();
int M=sc.nextInt();
int K=sc.nextInt();
int[][] stayDAYcost = new int[N][M+1];
sc.nextLine();
for (int i=0;i<N;i++){
String dan=sc.nextLine();
Arrays.fill(stayDAYcost[i],1_000_000_000);
List<Integer> lessons=new ArrayList<>();
for (int j=0;j<dan.length();j++){
if (dan.charAt(j)=='1'){
lessons.add(j);
}
}
Collections.sort(lessons);
int len=lessons.size();
for (int k=0;k<len;k++){
for (int prvih=0;prvih<=k;prvih++){
int zadnjih=k-prvih;
stayDAYcost[i][k]=Math.min(stayDAYcost[i][k],
lessons.get(len-1-zadnjih)-lessons.get(prvih)+1);
}
}
for (int j=len;j<=M;j++){
stayDAYcost[i][j]=0;
}
}
//System.out.println("TEST");
int[][] DP = new int[N+1][K+1];
Arrays.fill(DP[0], 0);
for (int i=1;i<=N;i++){
Arrays.fill(DP[i], 1_000_000_000);
}
for (int i=1;i<=N;i++){
for (int k=0;k<=K;k++){
for (int iz=0;iz<=k;iz++){
DP[i][k]=Math.min(DP[i][k], DP[i-1][k-iz]+stayDAYcost[i-1][Math.min(iz,M)]);
}
}
}
System.out.println(DP[N][K]);
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | d2c2a574cfc2e46365c8948e85bb2bfb | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 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 D {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
n = scan.nextInt(); m = scan.nextInt(); k = scan.nextInt();
grid = scan.nextGrid(n, m);
res = new int[n][k+1];
for(int i = 0; i < n; i++) Arrays.fill(res[i], 0x3f3f3f3f);
int[][] pre = new int[n][m];
for(int i = 0; i < n; i++) {
pre[i][0] = grid[i][0]=='1'?1:0;
for(int j = 1; j < m; j++) pre[i][j] = pre[i][j-1]+(grid[i][j]=='1'?1:0);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int p = j; p < m; p++) {
int took = pre[i][m-1]-pre[i][p]+(j==0?0:pre[i][j-1]);
if(took <= k) res[i][took] = Math.min(res[i][took], p-j+1);
}
}
}
for(int i = 0; i < n; i++) for(int j = 0; j <= k; j++) if(j >= pre[i][m-1]) res[i][j] = 0;
dp = new Integer[n][k+1];
out.println(go(0, k));
out.close();
}
static int n, m, k, p, res[][];
static char[][] grid;
static Integer[][] dp;
static int go(int at, int i) {
if(at == n) return 0;
if(dp[at][i] != null) return dp[at][i];
int ans = 0x3f3f3f3f;
for(int j = 0; j <= i; j++) ans = Math.min(ans, go(at+1, i-j)+res[at][j]);
return dp[at][i] = ans;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | b468fb46b36744046680eed55d348d9a | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D946
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n,m,k;
static String[] arr;
public static void main(String[] args)
{
int totalsum=0;
n=in.nextInt();
m=in.nextInt();
k=in.nextInt();
arr=new String[n+1];
int[] total=new int[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=in.nextLine();
for(int j=0;j<arr[i].length();j++)
{
if(arr[i].charAt(j)=='1')
total[i]++;
}
totalsum+=total[i];
}
if(k>=totalsum)
{
System.out.println(0);
return;
}
int[][] prefixsum=new int[n+1][m+1];
for(int i=1;i<=n;i++)
{
for(int j=0;j<arr[i].length();j++)
{
prefixsum[i][j+1]=prefixsum[i][j];
if(arr[i].charAt(j)=='1')
{
prefixsum[i][j+1]++;
}
}
}
int[][] dp1=new int[n+1][k+1];
for(int i=0;i<=n;i++)
{
Arrays.fill(dp1[i], mod);
}
for(int i=1;i<=n;i++)
{
for(int skip=0;skip<=k;skip++)
{
int left=1;
int right=1;
int toinclude=total[i]-skip;
if(toinclude<=0)
{
dp1[i][skip]=0;
continue;
}
while(left<=m && right<=m)
{
if(prefixsum[i][right]-prefixsum[i][left-1]>toinclude)
{
left++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]<toinclude)
{
right++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]==toinclude)
{
dp1[i][skip]=min(dp1[i][skip], right-left+1);
left++;
}
}
//out.print(dp1[i][skip]+" ");
}
//out.println();
}
int[][] dp=new int[n+1][k+1];
for(int i=2;i<=n;i++)
{
Arrays.fill(dp[i], mod);
}
for(int curr=0;curr<=k;curr++)
{
dp[1][curr]=dp1[1][curr];
}
for(int i=2;i<=n;i++)
{
dp[i][0]=dp1[i][0];
dp[i][0]+=dp[i-1][0];
}
for(int i=2;i<=n;i++)
{
for(int curr=0;curr<=k;curr++)
{
for(int prev=0;prev<=curr;prev++)
{
if(dp1[i][curr-prev]<mod && dp[i-1][prev]<mod)
dp[i][curr]=min(dp[i][curr], dp[i-1][prev]+dp1[i][curr-prev]);
}
}
}
long answer=dp[n][0];
for(int i=0;i<=k;i++)
{
answer=min(answer, dp[n][i]);
}
out.println(max(answer, 0));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 72acdff5315e43a34f4e5e3deb5ec144 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D946
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n,m,k;
static String[] arr;
public static void main(String[] args)
{
int totalsum=0;
n=in.nextInt();
m=in.nextInt();
k=in.nextInt();
arr=new String[n+1];
int[] total=new int[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=in.nextLine();
for(int j=0;j<arr[i].length();j++)
{
if(arr[i].charAt(j)=='1')
total[i]++;
}
totalsum+=total[i];
}
if(k>=totalsum)
{
System.out.println(0);
return;
}
int[][] prefixsum=new int[n+1][m+1];
for(int i=1;i<=n;i++)
{
for(int j=0;j<arr[i].length();j++)
{
prefixsum[i][j+1]=prefixsum[i][j];
if(arr[i].charAt(j)=='1')
{
prefixsum[i][j+1]++;
}
}
}
int[][] dp1=new int[n+1][k+1];
for(int i=0;i<=n;i++)
{
Arrays.fill(dp1[i], mod);
}
for(int i=1;i<=n;i++)
{
for(int skip=0;skip<=k;skip++)
{
int left=1;
int right=1;
int toinclude=total[i]-skip;
if(toinclude<=0)
{
dp1[i][skip]=0;
continue;
}
while(left<=m && right<=m)
{
if(prefixsum[i][right]-prefixsum[i][left-1]>toinclude)
{
left++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]<toinclude)
{
right++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]==toinclude)
{
dp1[i][skip]=min(dp1[i][skip], right-left+1);
left++;
}
}
//out.print(dp1[i][skip]+" ");
}
//out.println();
}
int[][] dp=new int[n+1][k+1];
for(int i=2;i<=n;i++)
{
Arrays.fill(dp[i], mod);
}
for(int curr=0;curr<=k;curr++)
{
dp[1][curr]=dp1[1][curr];
}
for(int i=2;i<=n;i++)
{
dp[i][0]=dp1[i][0];
dp[i][0]+=dp[i-1][0];
}
for(int i=2;i<=n;i++)
{
for(int curr=0;curr<=k;curr++)
{
for(int prev=0;prev<=curr;prev++)
{
if(dp1[i][curr-prev]<mod && dp[i-1][prev]<mod)
dp[i][curr]=min(dp[i][curr], dp[i-1][prev]+dp1[i][curr-prev]);
}
}
}
long answer=dp[n][0];
for(int i=0;i<=k;i++)
{
answer=min(answer, dp[n][i]);
}
out.println(max(answer, 0));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | e4adfead10211ab5e84bab41814227f8 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D946
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n,m,k;
static String[] arr;
public static void main(String[] args)
{
int totalsum=0;
n=in.nextInt();
m=in.nextInt();
k=in.nextInt();
arr=new String[n+1];
int[] total=new int[n+1];
for(int i=1;i<=n;i++)
{
arr[i]=in.nextLine();
for(int j=0;j<arr[i].length();j++)
{
if(arr[i].charAt(j)=='1')
total[i]++;
}
totalsum+=total[i];
}
if(k>=totalsum)
{
System.out.println(0);
return;
}
int[][] prefixsum=new int[n+1][m+1];
for(int i=1;i<=n;i++)
{
for(int j=0;j<arr[i].length();j++)
{
prefixsum[i][j+1]=prefixsum[i][j];
if(arr[i].charAt(j)=='1')
{
prefixsum[i][j+1]++;
}
}
}
int[][] dp1=new int[n+1][k+1];
for(int i=0;i<=n;i++)
{
Arrays.fill(dp1[i], mod);
}
for(int i=1;i<=n;i++)
{
for(int skip=0;skip<=k;skip++)
{
int left=1;
int right=1;
int toinclude=total[i]-skip;
if(toinclude<=0)
{
dp1[i][skip]=0;
continue;
}
while(left<=m && right<=m)
{
if(prefixsum[i][right]-prefixsum[i][left-1]>toinclude)
{
left++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]<toinclude)
{
right++;
continue;
}
if(prefixsum[i][right]-prefixsum[i][left-1]==toinclude)
{
dp1[i][skip]=min(dp1[i][skip], right-left+1);
left++;
}
}
//out.print(dp1[i][skip]+" ");
}
//out.println();
}
int[][] dp=new int[n+1][k+1];
for(int i=2;i<=n;i++)
{
Arrays.fill(dp[i], mod);
}
for(int curr=0;curr<=k;curr++)
{
dp[1][curr]=dp1[1][curr];
}
for(int i=2;i<=n;i++)
{
dp[i][0]=dp1[i][0];
dp[i][0]+=dp[i-1][0];
}
for(int i=2;i<=n;i++)
{
for(int curr=0;curr<=k;curr++)
{
for(int prev=0;prev<=curr;prev++)
{
if(dp1[i][curr-prev]<mod && dp[i-1][prev]<mod)
dp[i][curr]=min(dp[i][curr], dp[i-1][prev]+dp1[i][curr-prev]);
}
}
}
long answer=dp[n][k];
/*for(int i=0;i<=k;i++)
{
answer=min(answer, dp[n][i]);
}*/
out.println(max(answer, 0));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | be01c73bd1928b81a1b61e27125f2b10 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.Stream;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
List<Integer>[] map = Stream.generate(ArrayList::new).limit(n + 1).toArray(List[]::new);
for (int i = 1; i <= n; i++) {
char[] day = in.next().toCharArray();
for (int j = 0; j < m; j++) {
if (day[j] == '1') {
map[i].add(j);
}
}
}
int h = Math.min(k, m);
int[][] minByDay = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
int size = map[i].size();
for (int j = 0; j < size; j++) {
minByDay[i][j] = MI;
}
for (int j = 0; j < size; j++) {
for (int t = j; t < size; t++) {
int x = size - (t - j + 1);
minByDay[i][x] = Math.min(minByDay[i][x], map[i].get(t) - map[i].get(j) + 1);
}
}
}
int[][] minDay = new int[n + 1][k + 1];
for (int i = 2; i <= n; i++) {
for (int j = 0; j <= k; j++) {
minDay[i][j] = MI;
}
}
for (int j = 0; j <= h; j++) {
minDay[1][j] = minByDay[1][j];
}
for (int i = 2; i <= n; i++) {
for (int j = 0; j <= k; j++) {
for (int t = 0; t <= h; t++) {
if (t + j > k) break;
minDay[i][t + j] = Math.min(minDay[i][t + j], minDay[i - 1][j] + minByDay[i][t]);
}
}
}
printf(minDay[n][k]);
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 92ac4988b4cb2d48b5722f589b67a89a | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.DataInputStream;
import java.io.IOException;
public class Task946D {
public static class FastScanner {
protected static final int STRBUFFERLENGTH = 0x1000;
protected DataInputStream dataInputStream;
protected byte[] buffer = new byte[0x10000];
protected byte[] strbuffer = new byte[STRBUFFERLENGTH];
protected int bufferOffset;
protected int bufferLength;
protected boolean isEndOfFile;
public FastScanner() throws IOException {
dataInputStream = new DataInputStream(System.in);
Read();
}
protected void Read() throws IOException {
final int length = dataInputStream.read(buffer);
if (length > 0) {
bufferLength = length;
} else {
bufferLength = 0;
isEndOfFile = true;
}
bufferOffset = 0;
}
protected byte nextByte() throws IOException {
if (bufferOffset == bufferLength) {
if (!isEndOfFile) Read();
if (isEndOfFile) return 0;
}
return buffer[bufferOffset++];
}
public int nextInt() throws IOException {
int a = 0;
boolean isNegative = false;
byte b = nextByte();
while (b <= ' ') b = nextByte();
if (b == '-') {
isNegative = true;
b = nextByte();
}
while (b > ' ') {
a = a * 10 + (b - '0');
b = nextByte();
}
return isNegative ? -a : a;
}
public String nextLine() throws IOException {
String s = "";
int strbufferOffset = 0;
byte b = nextByte();
while (b <= ' ') b = nextByte();
do {
strbuffer[strbufferOffset++] = b;
if (strbufferOffset >= STRBUFFERLENGTH) {
s += new String(strbuffer, 0, STRBUFFERLENGTH);
strbufferOffset = 0;
}
b = nextByte();
} while (b != '\n' && b != '\r' && b != 0);
s += new String(strbuffer, 0, strbufferOffset);
return s;
}
}
public static final int MAX_N = 500;
public static final int MAX_M = 500;
public static final int INFINITY = MAX_N * MAX_M + 1;
public static void main(final String[] args) throws IOException {
final FastScanner scanner = new FastScanner();
final int n = scanner.nextInt();
final int m = scanner.nextInt();
final int k = scanner.nextInt();
final int minMK = Math.min(m, k);
// mn[i][j] - ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ°ΡΠΎΠ², Π΅ΡΠ»ΠΈ ΠΏΡΠΎΠΏΡΡΡΠΈΡΡ j Π·Π°Π½ΡΡΠΈΠΉ Π² i Π΄Π΅Π½Ρ
final int[][] mn = new int[n][minMK + 1];
int sumLessons = 0;
for (int i = 0; i < n; i++) {
final String s = scanner.nextLine();
final int[] pos = new int[m];
int numLessons = 0;
for (int j = 0; j < m; j++) {
if (s.charAt(j) == '1') {
pos[numLessons++] = j;
}
if (j <= minMK) mn[i][j] = INFINITY;
}
for (int j = 0; j < numLessons - 1; j++) {
for (int l = j + 1; l < numLessons; l++) {
final int numLessonsMissed = numLessons - (l - j + 1);
if (numLessonsMissed <= minMK) {
mn[i][numLessonsMissed] = Math.min(mn[i][numLessonsMissed], pos[l] - pos[j] + 1);
}
}
}
if (numLessons > 0 && numLessons - 1 <= minMK) mn[i][numLessons - 1] = 1;
if (numLessons <= minMK) mn[i][numLessons] = 0;
sumLessons += numLessons;
}
// ΡΡΠΈΠ²ΠΈΠ°Π»ΡΠ½ΡΠ΅ ΠΎΡΠ²Π΅ΡΡ
if (k >= sumLessons) {
System.out.println(0);
} else if (k == sumLessons - 1) {
System.out.println(1);
} else {
// dp[i][j] - ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ°ΡΠΎΠ², Π΅ΡΠ»ΠΈ ΠΏΡΠΎΠΏΡΡΡΠΈΡΡ j Π·Π°Π½ΡΡΠΈΠΉ Π·Π° i Π΄Π½Π΅ΠΉ
final int[][] dp = new int[n][k + 1];
for (int j = 0; j <= k; j++) {
if (j <= minMK) dp[0][j] = mn[0][j];
else dp[0][j] = INFINITY;
}
for (int i = 1; i < n; i++) {
for (int j = 0; j <= k; j++) {
dp[i][j] = INFINITY;
for (int l = 0; l <= j; l++) {
if (j - l <= minMK) {
final int minDP = dp[i - 1][l] + mn[i][j - l];
dp[i][j] = Math.min(dp[i][j], minDP);
}
}
}
}
System.out.println(dp[n - 1][k]);
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | a0376ee1669f1578f8ece7a38154d65f | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jay Leeds
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
ArrayList<ArrayList<Integer>> data = new ArrayList<>();
for (int i = 0; i < n; i++) {
String s = in.nextString();
data.add(new ArrayList<>());
for (int j = 0; j < m; j++) {
if (s.charAt(j) == '1') {
data.get(i).add(j);
}
}
}
int[][] minDp = new int[n][k + 1];
for (int i = 0; i < n; i++) for (int j = 0; j <= k; j++) minDp[i][j] = 501;
for (int i = 0; i < n; i++) {
for (int j = data.get(i).size(); j <= k; j++) minDp[i][j] = 0;
for (int j = 0; j < data.get(i).size(); j++) {
for (int x = j; x < data.get(i).size(); x++) {
int numSkip = j + data.get(i).size() - 1 - x;
if (numSkip <= k) {
minDp[i][numSkip] = Math.min(minDp[i][numSkip], data.get(i).get(x) - data.get(i).get(j) + 1);
}
}
}
}
int[] dpTotals = Arrays.copyOf(minDp[0], k + 1);
for (int i = 1; i < n; i++) {
int[] dpOld = Arrays.copyOf(dpTotals, k + 1);
for (int j = 0; j <= k; j++) dpTotals[j] = Integer.MAX_VALUE;
for (int j = 0; j <= k; j++) {
for (int x = 0; j + x <= k; x++) {
dpTotals[j + x] = Math.min(dpTotals[j + x], dpOld[j] + minDp[i][x]);
}
}
}
out.printLine(dpTotals[k]);
}
}
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 printLine(int i) {
writer.println(i);
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream; //Fast IO by Egor Kulikov, modified by myself
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 803c9723a5678c93ae4d430663d53e93 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | //package codeforces.Educational39;
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 D
{
static int[][] memo;
static int n, m, k;
static char[][] day;
static char[] cur;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
best = new int[m+3];
cum = new int[m];
day = new char[n][];
for (int i = 0; i < n; i++)
day[i] = sc.next().toCharArray();
memo = new int[n+3][k+3];
vis = new boolean[m+2][m+2];
for (int d = n-1; d >= 0; d--)
{
// prepare day
for (int i = 0; i < vis.length; i++)
for (int j = 0; j < vis.length; j++)
vis[i][j] = false;
cur = day[d];
cum[0] = cur[0] == '1'?1:0;
for (int i = 1; i < cum.length; i++)
cum[i] = cum[i-1]+(cur[i]=='1'?1:0);
Arrays.fill(best, m+1);
for (int i = cum[m-1]; i < best.length; i++)
best[i] = 0;
best(0,m-1);
Arrays.fill(memo[d], 500000000);
for (int rem = 0; rem <= k; rem++)
{
for (int rmv = 0; rmv <= Math.min(cum[m-1], rem); rmv++)
memo[d][rem] = Math.min(memo[d][rem], best[rmv] + memo[d+1][rem-rmv]);
}
}
System.out.println(memo[0][k]);
pw.flush();
pw.close();
}
static int[] best;
static int[] cum;
static boolean vis[][];
private static void best(int i, int j)
{
if(j < i)
return;
if(vis[i][j])
return;
vis[i][j] = true;
int removed = cum[m-1] - cum[j];
if(i > 0)
removed += cum[i-1];
best[removed] = Math.min(j-i+1, best[removed]);
if(i == j && cur[i] == '0')
best[removed] = Math.min(0, best[removed]);
best(i+1, j);
best(i, j-1);
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 5ad7aba266bef53ef31a2c44b28e2f9c | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private long[][] dp;
private static final int INF = Integer.MAX_VALUE;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
String s[] = new String[n];
int classSkiped[][] = new int[n][];
for (int i = 0; i < n; i++) {
s[i] = in.next();
classSkiped[i] = classSkiped(s[i]);
}
dp = new long[502][502];
for (long d1[] : dp) Arrays.fill(d1, -1);
out.println(findMinHours(0, k, classSkiped));
}
private long findMinHours(int i, int k, int classSkiped[][]) {
if (k < 0) {
return INF;
}
if (dp[i][k] != -1) return dp[i][k];
if (i >= classSkiped.length) {
return 0;
} else {
long minHours = Integer.MAX_VALUE;
for (int spentHours = 0; spentHours < classSkiped[i].length; spentHours++) {
minHours = Math.min(minHours, findMinHours(i + 1, k - classSkiped[i][spentHours], classSkiped) + spentHours);
}
return dp[i][k] = minHours;
}
}
private int[] classSkiped(String s) {
int sum[] = new int[s.length()];
sum[0] = s.charAt(0) == '1' ? 1 : 0;
for (int i = 1; i < s.length(); i++) {
sum[i] = sum[i - 1] + (s.charAt(i) == '1' ? 1 : 0);
}
int total = sum[s.length() - 1];
int skiped[] = new int[s.length() + 1];
Arrays.fill(skiped, Integer.MAX_VALUE);
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
int hours = j - i + 1;
int end = i > 0 ? sum[i - 1] : 0;
int skip = total - (sum[j] - end);
skiped[hours] = Math.min(skiped[hours], skip);
}
}
skiped[0] = total;
return skiped;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public int nextInt() {
return readInt();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 30042d0d62433e9590cdf56964ef02e8 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.PrintWriter;
public class D946
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt(),m=in.nextInt(),k=in.nextInt();
int dp[][]=new int[n][k+1];
for(int i=0;i<n;i++)
{
char c[]=in.next().toCharArray();
int dp1[]=new int[k+1];
int a[]=new int[m];
int temp=0;
for(int j=0;j<m;j++)
{
if(c[j]=='1')
a[temp++]=j;
}
for(int j=0;j<Math.min(temp,k+1);j++)
dp1[j]=1000000000;
for(int j=0;j<temp;j++)
{
int del=j;
if(del>k)
break;
for(int l=temp-1;l>=j;l--)
{
if(del>k)
break;
dp1[del]=Math.min(dp1[del],a[l]-a[j]+1);
del++;
}
}
if(i==0)
{
for(int j=0;j<=k;j++)
dp[0][j]=dp1[j];
}
else
{
for(int j=0;j<=k;j++)
{
dp[i][j]=1000000000;
for(int l=0;l<=j;l++)
{
dp[i][j]=Math.min(dp[i][j],dp[i-1][j-l]+dp1[l]);
}
}
}
}
out.println(dp[n-1][k]);
out.close();
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 7ce10b7cffce3b3136d118910cc975bc | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
// static long oo = (long)1e15;
static int mod = 1_000_000_007;
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, -1, 0, 1};
static int M = 2005;
static double EPS = 1e-13;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
char[][] a = new char[n][];
for(int i = 0; i < n; ++i)
a[i] = in.readString().toCharArray();
// int n = 500;
// int m = 500;
// int k = 500;
// char[][] a = new char[n][m];
// for(int i = 0; i < n; ++i)
// for(int j = 0; j < m; ++j)
// a[i][j] = '1';
ArrayList<Integer>[] c = new ArrayList[n];
for(int i = 0; i < n; ++i) {
c[i] = new ArrayList<>();
for(int j = 0; j < m; ++j) {
if(a[i][j] == '1')
c[i].add(j);
}
}
int[][] minT = new int[n][m+1];
for(int i = 0; i < n; ++i) {
for(int skip = 0; skip < c[i].size(); ++skip) {
minT[i][skip] = oo;
for(int l = 0, r = c[i].size() - 1 - skip; r < c[i].size(); ++l, ++r) {
int t = c[i].get(r) - c[i].get(l) + 1;
minT[i][skip] = Math.min(minT[i][skip], t);
}
}
}
int[][] dp = new int[n][k+1];
for(int i = 0; i < n; ++i) {
for(int j = 0; j <= k; ++j) {
dp[i][j] = oo;
for(int x = 0, b = Math.min(c[i].size(), j); x <= b; ++x) {
dp[i][j] = Math.min(dp[i][j], (i == 0 ? 0 : dp[i-1][j - x]) + minT[i][x] );
}
}
}
int ans = dp[n-1][k];
System.out.println(ans);
out.close();
}
static int find(int[] g, int x) {
return g[x] = g[x] == x ? x : find(g, g[x]);
}
static void union(int[] g, int[] size, int x, int y) {
x = find(g, x); y = find(g, y);
if(x == y)
return;
if(size[x] < size[y]) {
g[x] = y;
size[y] += size[x];
}
else {
g[y] = x;
size[x] += size[y];
}
}
static class Segment {
Segment left, right;
int size, minIdx;
// int time, lazy;
public Segment(int[] a, int l, int r) {
super();
if(l == r) {
this.minIdx = l;
this.size = 1;
return;
}
int mid = (l + r) / 2;
left = new Segment(a, l, mid);
right = new Segment(a, mid+1, r);
if(a[left.minIdx] <= a[right.minIdx])
this.minIdx = left.minIdx;
else
this.minIdx = right.minIdx;
this.size = left.size + right.size;
}
boolean covered(int ll, int rr, int l, int r) {
return ll <= l && rr >= r;
}
boolean noIntersection(int ll, int rr, int l, int r) {
return ll > r || rr < l;
}
// void lazyPropagation() {
// if(lazy != 0) {
// if(left != null) {
// left.setLazy(this.time, this.lazy);
// right.setLazy(this.time, this.lazy);
// }
// else {
// val = lazy;
// }
// }
// }
// void setLazy(int time, int lazy) {
// if(this.time != 0 && this.time <= time)
// return;
// this.time = time;
// this.lazy = lazy;
// }
int querySize(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return 0;
if(covered(ll, rr, l, r))
return size;
int mid = (l + r) / 2;
int leftSize = left.querySize(ll, rr, l, mid);
int rightSize = right.querySize(ll, rr, mid+1, r);
return leftSize + rightSize;
}
int query(int k, int l, int r) {
Segment trace = this;
while(l < r) {
int mid = (l + r) / 2;
if(trace.left.size > k) {
trace = trace.left;
r = mid;
}
else {
k -= trace.left.size;
trace = trace.right;
l = mid + 1;
}
}
return l;
}
void update(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return;
if(covered(ll, rr, l, r)) {
// setLazy(time, knight);
this.minIdx = -1;
this.size = 0;
return;
}
int mid = (l + r) / 2;
left.update(ll, rr, l, mid);
right.update(ll, rr, mid+1, r);
this.size = left.size + right.size;
}
}
static long pow(long a, long n, long mod) {
if(n == 0)
return 1;
if(n % 2 == 1)
return a * pow(a, n-1, mod) % mod;
long x = pow(a, n / 2, mod);
return x * x % mod;
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static BigInteger lcm2(long a, long b) {
long g = gcd(a, b);
BigInteger gg = BigInteger.valueOf(g);
BigInteger aa = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return aa.multiply(bb).divide(gg);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(Object[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
Object t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static BigInteger gcd(BigInteger a, BigInteger b) {
return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
// @Override
// public int compareTo(Pair o) {
// return this.first != o.first ? o.first - this.first : o.second - this.second;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
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 | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 396b4b34080da7f2e4bdab3f90c3578a | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main extends Thread {
private static FastScanner scanner = new FastScanner(System.in);
private static PrintWriter writer = new PrintWriter(System.out);
// private static Scanner scanner = new Scanner(System.in);
private static ArrayList<Integer>[] table;
private static int n;
private static int m;
private static int k;
private static int[][] mn;
private static int[][] dp;
public static void main(String[] args) throws IOException {
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
table = new ArrayList[n];
for (int i = 0; i < n; i++) {
table[i] = new ArrayList<>();
char[] chars = scanner.next().toCharArray();
for (int j = 0; j < m; j++) {
if (chars[j] == '1') {
table[i].add(j);
}
}
}
mn = new int[n][k + 1];
preComputeMN();
// printArray(mn);
dp = new int[n][k + 1];
computeDP();
// printArray(dp);
System.out.println(dp[n - 1][k]);
}
private static void computeDP() {
dp[0] = mn[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < k + 1; j++) {
dp[i][j] = getMin(i, j);
}
}
}
private static int getMin(int i, int j) {
int min = Integer.MAX_VALUE;
for (int k = 0; k <= j; k++) {
min = Integer.min(min, mn[i][k] + dp[i - 1][j - k]);
}
return min;
}
private static void preComputeMN() {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
mn[i][j] = getMinTimeInDayWithK(i, j);
}
}
}
private static int getMinTimeInDayWithK(int i, int k) {
if (k >= table[i].size()) return 0;
int frameSize = table[i].size() - k;
int min = Integer.MAX_VALUE;
for (int j = 0; j <= k; j++) {
min = Integer.min(min,
table[i].get(j + frameSize - 1) - table[i].get(j) + 1);
}
return min;
}
static class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private static void printArray(int[][] array) {
for (int i = 0; i < array.length; i++) {
System.out.print("\n");
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
}
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U first;
public V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public int hashCode() {
return (first == null ? 0 : first.hashCode() * 31) +
(second == null ? 0 : second.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (first == null ? p.first == null : first.equals(p.first)) &&
(second == null ? p.second == null : second.equals(p.second));
}
public int compareTo(Pair<U, V> b) {
int cmpU = first.compareTo(b.first);
return cmpU != 0 ? cmpU : second.compareTo(b.second);
}
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | ef00c27565c58d1d5bec6f73e9b60859 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private static ArrayList<ArrayList<Integer>> classes = new ArrayList<ArrayList<Integer>>();
private static ArrayList<ArrayList<Integer>> gaps = new ArrayList<ArrayList<Integer>>();
private static ArrayList<ArrayList<Integer>> prefixes = new ArrayList<ArrayList<Integer>>();
private static int[][] matrix = new int[502][502];
private static int[][] dp = new int[502][502];
private static int N, M, K;
private static final int INF = 1 << 29;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
for (int i = 0; i < N; i++) {
classes.add(new ArrayList<Integer>());
gaps.add(new ArrayList<Integer>());
prefixes.add(new ArrayList<Integer>());
}
for (int i = 0; i < N; i++) {
String str = f.readLine();
for (int k = 0; k < M; k++) {
if (str.substring(k, k + 1).equals("1")) {
classes.get(i).add(k);
}
}
}
for (int i = 0; i < N; i++) {
for (int k = 0; k < classes.get(i).size() - 1; k++) {
gaps.get(i).add(classes.get(i).get(k + 1) - classes.get(i).get(k));
}
}
for (int i = 0; i < N; i++) {
prefixes.get(i).add(0);
for (int k = 0; k < gaps.get(i).size(); k++) {
prefixes.get(i).add(prefixes.get(i).get(k) + gaps.get(i).get(k));
}
}
for (int i = 0; i < 502; i++) {
Arrays.fill(matrix[i], Integer.MAX_VALUE);
Arrays.fill(dp[i], -1);
}
for (int i = 0; i < N; i++) {
init(i);
}
for (int i = 0; i < 502; i++) {
for (int k = 0; k < 502; k++) {
if (matrix[i][k] == Integer.MAX_VALUE) {
matrix[i][k] = 0;
}
}
}
System.out.println(dfs(0, 0));
}
public static int dfs(int day, int count) {
if (count > K) {
return INF;
}
if (day == N)
return 0;
if (dp[day][count] != -1) {
return dp[day][count];
}
int result = INF;
for (int i = 0; i <= classes.get(day).size(); i++) {
result = Math.min(result, dfs(day + 1, count + i) + matrix[day][i]);
}
dp[day][count] = result;
return result;
}
public static void init(int day) {
for (int left = 0; left < classes.get(day).size(); left++) {
for (int right = left; right < classes.get(day).size(); right++) {
int skip = classes.get(day).size() - (right - left) - 1;
int value = query(day, left, right);
matrix[day][skip] = Math.min(matrix[day][skip], value);
}
}
}
public static int query(int day, int left, int right) {
return prefixes.get(day).get(right) - prefixes.get(day).get(left) + 1;
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 6e7a613a5737751b1fb34bea3e61fdc6 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
public class D {
public static void main(String cd[]) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String nmk[] = in.readLine().split(" ");
int n = Integer.parseInt(nmk[0]);
int m = Integer.parseInt(nmk[1]);
int k = Integer.parseInt(nmk[2]);
ArrayList<Integer> rows[] = new ArrayList[n + 1];
for(int i=1;i<=n;i++){
rows[i] = new ArrayList<>();
String s = in.readLine();
for(int j =0; j<m;j++){
if(s.charAt(j) == '1'){
rows[i].add(j);
}
}
}
int dp[][] = new int[n + 1][k+1];
for(int i = 1 ;i <= n ;i++){
for(int j=0 ;j <= k ;j++){
dp[i][j] = Integer.MAX_VALUE;
}
}
for(int i =1 ;i<=n; i++){
int ans[] = new int[k+1];
int totalNoOfOnes = rows[i].size();
for (int j = 0; j <= k; j++) {
int needNo = totalNoOfOnes - j;
if(needNo <= 0){
break;
}
int step = needNo - 1;
ans[j] = m;
for (int l = 0; l + step < rows[i].size(); l++) {
ans[j] = Math.min(ans[j],rows[i].get(l + step) - rows[i].get(l) +1);
}
}
for(int j=0; j<=k ;j++){
for(int l =0; l<=j ;l++){
dp[i][j] = Math.min(dp[i][j] , dp[i - 1][l] + ans[j - l]);
}
}
}
int ans =Integer.MAX_VALUE;
for(int i=0; i<=k;i++){
ans = Math.min(dp[n][i] , ans);
}
out.println(ans);
out.close();
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 3b9bf32ee98ef6e73d13493ffcb2bf36 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.util.*;
import java.io.*;
import java.io.FileWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
final int[][] dirs8 = {{0,1}, {0,-1}, {-1,0}, {1,0}, {1,1},{1,-1},{-1,1},{-1,-1}};
final int[][] dirs4 = {{0,1}, {0,-1}, {-1,0}, {1,0}};
final int MOD = 1000000007; //998244353;
final int WALL = -1;
final int EMPTY = -2;
final int VISITED = 1;
final int FULL = 2;
final int START = 1;
final int END = 0;
long[] fac;
//long[] ifac;
//long[] fac = new long[100];
//long[] ifac = new long[100001];
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
//int nt = in.nextInt();
int nt = 1;
StringBuilder sb = new StringBuilder();
//fac[0] = 1;
//ifac[0] = 1;
//for (int i = 1; i <= 20; i++) {
// fac[i] = fac[i-1] * i % MOD;
// ifac[i] = ifac[i-1] * inv(i) % MOD;
//}
long[][] C = new long[19][11];
// Caculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= 18; i++)
{
for (int j = 0; j <= min(i, 10); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using previously
// stored values
else
C[i][j] = C[i - 1][j - 1] +
C[i - 1][j];
}
}
//long[] invs = new long[101];
//for (int i = 1; i <= 100; i++) invs[i] = inv(i);
for (int it = 0; it < nt; it++)
{
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
final int INF = n * m * 10;
char[][] days = new char[n][];
for (int i = 0; i < n; i++)
days[i] = in.next().toCharArray();
int[][] dp = new int[n+1][k+1];
int[] pos = new int[m];
int[] cost = new int[m+1];
for (int i = 1; i <= n; i++)
{
//pre-process days[i-1]
int cnt1 = 0;
for (char c : days[i-1])
if (c == '1') cnt1++;
int cur = 0;
for (int j = 0; j < m; j++) {
if (days[i-1][j] == '1') pos[cur++] = j;
}
for (int j = 0; j < cnt1; j++)
{
cost[j] = m;
for (int f = 0, e = f + cnt1 - j - 1; e < cnt1; f++, e++)
cost[j] = Math.min(cost[j], pos[e] - pos[f] + 1);
}
for (int j = cnt1; j <= m; j++) cost[j] = 0;
for (int j = 0; j <= k; j++)
{
int hi = Math.min(cnt1, j);
dp[i][j] = INF;
for (int t = 0; t <= hi; t++)
{
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-t] + cost[t]);
}
}
}
sb.append(dp[n][k] + "\n");
}
System.out.print(sb);
}
private boolean rep2(char[] a, int len)
{
for (int i = 0, j = len; i < len; i++, j++)
if (a[i] != a[j]) return false;
return true;
}
private long[][] matIdentity(int n)
{
long[][] a = new long[n][n];
for (int i = 0; i < n; i++)
a[i][i] = 1;
return a;
}
private long[][] matPow(long[][] mat0, long p)
{
int n = mat0.length;
long[][] ans = matIdentity(n);
long[][] mat = matCopy(mat0);
while (p > 0)
{
if (p % 2 == 1){
ans = matMul(ans, mat);
}
p /= 2;
mat = matMul(mat, mat);
}
return ans;
}
private long[][] matCopy(long[][] a)
{
int n = a.length;
long[][] b = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
b[i][j] = a[i][j];
return b;
}
private long[][] matMul(long[][] a, long[][] b)
{
int n = a.length;
long[][] c = new long[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
}
}
return c;
}
private long[] matMul(long[][] a, long[] b)
{
int n = a.length;
long[] c = new long[n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
c[i] = (c[i] + a[i][j] * b[j]) % MOD;
}
return c;
}
class Mark implements Comparable<Mark> {
int type, h;
long x;
public Mark(int h, long x, int type)
{
this.h = h;
this.x = x;
this.type = type;
}
@Override
public int compareTo(Mark o)
{
if (this.x == o.x) return type - o.type; // let end comes before start
return Long.compare(x, o.x);
}
}
private boolean coLinear(int[] p, int[] q, int[] r)
{
return 1L * (p[1] - r[1]) * (q[0] - r[0]) == 1L * (q[1] - r[1]) * (p[0] - r[0]);
}
private void fill(char[] a, int lo, int c, char letter)
{
//System.out.println("fill " + lo + " " + c + " " + letter);
for (int i = lo; i < lo + c; i++) a[i] = letter;
}
private int cntBitOne(String s){
int c = 0, n = s.length();
for (int i = 0; i < n; i++)
if (s.charAt(i) == '1') c++;
return c;
}
class DSU {
int n;
int[] par;
int[] sz;
int nGroup;
public DSU(int n)
{
this.n = n;
par = new int[n];
sz = new int[n];
for (int i = 0; i < n; i++){
par[i] = i;
sz[i] = 1;
}
nGroup = n;
}
private boolean add(int p, int q) {
int rp = find(p);
int rq = find(q);
if (rq == rp) return false;
if (sz[rp] <= sz[rq]) {
sz[rq] += sz[rp];
par[rp] = rq;
}else {
sz[rp] += sz[rq];
par[rq] = rp;
}
nGroup--;
return true;
}
private int find(int p)
{
int r = p;
while (par[r] != r) r = par[r];
while (r != p) {
int t = par[p];
par[p] = r;
p = t;
}
return r;
}
}
private int[] build_z_function(String s)
{
int n = s.length();
int[] zfun = new int[n];
int l = -1, r = -1;
for (int i = 1; i < n; i++)
{
// Set the start value
if (i <= r)
zfun[i] = Math.min(zfun[i-l], r - i + 1);
while (i + zfun[i] < n && s.charAt(i + zfun[i]) == s.charAt(zfun[i]))
zfun[i]++;
if (i + zfun[i] - 1> r){
l = i;
r = i + zfun[i] - 1;
}
}
if (test)
{
System.out.println("Z-function of " + s);
for (int i = 0; i < n; i++) System.out.print(zfun[i] + " ");
System.out.println();
}
return zfun;
}
class BIT {
int[] bit;
int n;
public BIT(int n){
this.n = n;
bit = new int[n+1];
}
private int query(int p)
{
int sum = 0;
for (; p > 0; p -= (p & (-p)))
sum += bit[p];
return sum;
}
private void add(int p, int val)
{
//System.out.println("add to BIT " + p);
for (; p <= n; p += (p & (-p)))
bit[p] += val;
}
}
private List<Integer> getMinFactor(int sum)
{
List<Integer> factors = new ArrayList<>();
for (int sz = 2; sz <= sum / sz; sz++){
if (sum % sz == 0) {
factors.add(sz);
factors.add(sum / sz);
}
}
if (factors.size() == 0)
factors.add(sum);
return factors;
}
/* Tree class */
class Tree {
int V = 0;
int root = 0;
List<Integer>[] nbs;
int[][] timeRange;
int[] subTreeSize;
int t;
boolean dump = false;
public Tree(int V, int root)
{
if (dump)
System.out.println("build tree with size = " + V + ", root = " + root);
this.V = V;
this.root = root;
nbs = new List[V];
subTreeSize = new int[V];
for (int i = 0; i < V; i++)
nbs[i] = new ArrayList<>();
}
public void doneInput()
{
dfsEuler();
}
public void addEdge(int p, int q)
{
nbs[p].add(q);
nbs[q].add(p);
}
private void dfsEuler()
{
timeRange = new int[V][2];
t = 1;
dfs(root);
}
private void dfs(int node)
{
if (dump)
System.out.println("dfs on node " + node + ", at time " + t);
timeRange[node][0] = t;
for (int next : nbs[node]) {
if (timeRange[next][0] == 0)
{
++t;
dfs(next);
}
}
timeRange[node][1] = t;
subTreeSize[node] = t - timeRange[node][0] + 1;
}
public List<Integer> getNeighbors(int p) {
return nbs[p];
}
public int[] getSubTreeSize(){
return subTreeSize;
}
public int[][] getTimeRange()
{
if (dump){
for (int i = 0; i < V; i++){
System.out.println(i + ": " + timeRange[i][0] + " - " + timeRange[i][1]);
}
}
return timeRange;
}
}
/* segment tree */
class SegTree {
int[] a;
int[] tree;
int[] treeMin;
int[] treeMax;
int[] lazy;
int n;
boolean dump = false;
public SegTree(int n)
{
if (dump)
System.out.println("create segTree with size " + n);
this.n = n;
treeMin = new int[n*4];
treeMax = new int[n*4];
lazy = new int[n*4];
}
public SegTree(int n, int[] a) {
this(n);
this.a = a;
buildTree(1, 0, n-1);
}
private void buildTree(int node, int lo, int hi)
{
if (lo == hi) {
tree[node] = lo;
return;
}
int m = (lo + hi) / 2;
buildTree(node * 2, lo, m);
buildTree(node * 2 + 1, m + 1, hi);
pushUp(node, lo, hi);
}
private void pushUp(int node, int lo, int hi)
{
if (lo >= hi) return;
// note that, if we need to call pushUp on a node, then lazy[node] must be zero.
//the true value is the value + lazy
treeMin[node] = Math.min(treeMin[node * 2] + lazy[node * 2], treeMin[node * 2 + 1] + lazy[node * 2 + 1]);
treeMax[node] = Math.max(treeMax[node * 2] + lazy[node * 2], treeMax[node * 2 + 1] + lazy[node * 2 + 1]);
// add combine fcn
}
private void pushDown(int node, int lo, int hi)
{
if (lazy[node] == 0) return;
int lz = lazy[node];
lazy[node] = 0;
treeMin[node] += lz;
treeMax[node] += lz;
if (lo == hi) return;
int mid = (lo + hi) / 2;
lazy[node * 2] += lz;
lazy[node * 2 + 1] += lz;
}
public int rangeQueryMax(int fr, int to)
{
return rangeQueryMax(1, 0, n-1, fr, to);
}
public int rangeQueryMax(int node, int lo, int hi, int fr, int to)
{
if (lo == fr && hi == to)
return treeMax[node] + lazy[node];
int mid = (lo + hi) / 2;
pushDown(node, lo, hi);
if (to <= mid) {
return rangeQueryMax(node * 2, lo, mid, fr, to);
}else if (fr > mid)
return rangeQueryMax(node * 2 + 1, mid + 1, hi, fr, to);
else {
return Math.max(rangeQueryMax(node * 2, lo, mid, fr, mid),
rangeQueryMax(node * 2 + 1, mid + 1, hi, mid + 1, to));
}
}
public int rangeQueryMin(int fr, int to)
{
return rangeQueryMin(1, 0, n-1, fr, to);
}
public int rangeQueryMin(int node, int lo, int hi, int fr, int to)
{
if (lo == fr && hi == to)
return treeMin[node] + lazy[node];
int mid = (lo + hi) / 2;
pushDown(node, lo, hi);
if (to <= mid) {
return rangeQueryMin(node * 2, lo, mid, fr, to);
}else if (fr > mid)
return rangeQueryMin(node * 2 + 1, mid + 1, hi, fr, to);
else {
return Math.min(rangeQueryMin(node * 2, lo, mid, fr, mid),
rangeQueryMin(node * 2 + 1, mid + 1, hi, mid + 1, to));
}
}
public void rangeUpdate(int fr, int to, int delta){
rangeUpdate(1, 0, n-1, fr, to, delta);
}
public void rangeUpdate(int node, int lo, int hi, int fr, int to, int delta){
pushDown(node, lo, hi);
if (fr == lo && to == hi)
{
lazy[node] = delta;
return;
}
int m = (lo + hi) / 2;
if (to <= m)
rangeUpdate(node * 2, lo, m, fr, to, delta);
else if (fr > m)
rangeUpdate(node * 2 + 1, m + 1, hi, fr, to, delta);
else {
rangeUpdate(node * 2, lo, m, fr, m, delta);
rangeUpdate(node * 2 + 1, m + 1, hi, m + 1, to, delta);
}
// re-set the in-variant
pushUp(node, lo, hi);
}
public int query(int node, int lo, int hi, int fr, int to)
{
if (fr == lo && to == hi)
return tree[node];
int m = (lo + hi) / 2;
if (to <= m)
return query(node * 2, lo, m, fr, to);
else if (fr > m)
return query(node * 2 + 1, m + 1, hi, fr, to);
int lid = query(node * 2, lo, m, fr, m);
int rid = query(node * 2 + 1, m + 1, hi, m + 1, to);
return a[lid] >= a[rid] ? lid : rid;
}
}
private long inv(long v)
{
return pow(v, MOD-2);
}
private long pow(long v, long p)
{
long ans = 1;
while (p > 0)
{
if (p % 2 == 1)
ans = ans * v % MOD;
v = v * v % MOD;
p = p / 2;
}
return ans;
}
private double dist(double x, double y, double xx, double yy)
{
return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
}
private int mod_add(int a, int b) {
int v = a + b;
if (v >= MOD) v -= MOD;
return v;
}
private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2);
if (x3 > x2 || y4 < y1 || y3 > y2) return 0L;
//(x3, ?, x2, ?)
int yL = Math.max(y1, y3);
int yH = Math.min(y2, y4);
int xH = Math.min(x2, x4);
return f(x3, yL, xH, yH);
}
//return #black cells in rectangle
private long f(int x1, int y1, int x2, int y2) {
long dx = 1L + x2 - x1;
long dy = 1L + y2 - y1;
if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0)
return 1L * dx * dy / 2;
return 1L * dx * dy / 2 + 1;
}
private int distM(int x, int y, int xx, int yy) {
return abs(x - xx) + abs(y - yy);
}
private boolean less(int x, int y, int xx, int yy) {
return x < xx || y > yy;
}
private int mul(int x, int y) {
return (int)(1L * x * y % MOD);
}
private int nBit1(int v) {
int v0 = v;
int c = 0;
while (v != 0) {
++c;
v = v & (v - 1);
}
return c;
}
private long abs(long v) {
return v > 0 ? v : -v;
}
private int abs(int v) {
return v > 0 ? v : -v;
}
private int common(int v) {
int c = 0;
while (v != 1) {
v = (v >>> 1);
++c;
}
return c;
}
private void reverse(char[] a, int i, int j) {
while (i < j) {
swap(a, i++, j--);
}
}
private void swap(char[] a, int i, int j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
}
private int gcd(int x, int y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private long gcd(long x, long y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private int max(int a, int b) {
return a > b ? a : b;
}
private long max(long a, long b) {
return a > b ? a : b;
}
private int min(int a, int b) {
return a > b ? b : a;
}
private long min(long a, long b) {
return a > b ? b : a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
return null;
//e.printStackTrace();
}
return str;
}
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 546f052b287169b35983656a24f08d97 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.flush();out.close();
}
static class TaskE {
class pair{
int id,l,r,lv,rv;pair(int a,int b,int c,int d,int e){id=a;l=b;r=c;lv=d;rv=e;}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt(),m=in.nextInt(),k=in.nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)s[i]=in.next().trim();
ArrayList<Integer> al[]=new ArrayList[n];
for(int i=0;i<n;i++){
al[i]=new ArrayList<>();
for(int j=0;j<m;j++){
if(s[i].charAt(j)=='1')al[i].add(j);
}
}
int p[][]=new int[501][501];
for(int i=0;i<n;i++){
int L=al[i].size();
for(int j=0;j<=L-1;j++){
p[i+1][j]=m;
for(int z=0;z<=j;z++){
p[i+1][j]=Math.min(p[i+1][j],al[i].get(L-(j-z)-1)-al[i].get(z)+1);
}
}
}
int dp[][]=new int[501][501];
for(int i=1;i<=n;i++){
for(int j=0;j<=k;j++){dp[i][j]=100000000;
for(int z=0;z<=j;z++){
dp[i][j]=Math.min(dp[i-1][z]+p[i][j-z],dp[i][j]);
}
}
}out.print(dp[n][k]);
}
/*pair ja[][];long w[];int from[],to[],c[];
void make(int n,int m,InputReader in){
ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1];
for(int i=0;i<m;i++){
int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong();
c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt;
}
for(int i=1;i<=n;i++){
ja[i]=new pair[c[i]];c[i]=0;
}
for(int i=0;i<m;i++){
ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]);
ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]);
}
}*/
int[] radixSort(int[] f){ return radixSort(f, f.length); }
int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
st = null;
}
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;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | cdde81ae2442a38501885f186aa6df5c | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | //package info.stochastic;
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int[][] week;
void solveWeek(String w1, int index, int kValue) {
List<Integer> w = new ArrayList<>();
for (int i = 0; i < w1.length(); i++) {
if (w1.charAt(i) == '1') {
w.add(i);
}
}
for (int k = 0; k < Math.min(kValue + 1, w.size() + 1); k++) {
week[index][k] = Integer.MAX_VALUE / 2;
if (k == w.size()) {
week[index][k] = 0;
continue;
}
for (int i = 0, j = w.size() - 1 - k; j < w.size(); i++, j++) {
week[index][k] = Math.min(week[index][k], w.get(j) - w.get(i) + 1);
}
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt() + 1;
int k = in.nextInt();
int[][] dp = new int[n][k + 1];
week = new int[n][k + 1];
for (int w = 0; w < n; w++) {
String s = in.next();
solveWeek(s, w, k);
if (w == 0) {
System.arraycopy(week[0], 0, dp[0], 0, Math.min(k + 1, m));
continue;
}
for (int kk = 0; kk <= k; kk++) {
dp[w][kk] = Integer.MAX_VALUE / 2;
for (int prev = 0, next = kk; prev <= kk; prev++, next--) {
dp[w][kk] = Math.min(dp[w][kk], dp[w - 1][prev] + week[w][next]);
}
}
}
int ans = Integer.MAX_VALUE / 2;
for (int i = 0; i < k + 1; i++) {
ans = Math.min(ans, dp[n - 1][i]);
}
out.print(ans);
}
}
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 | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 2de7d28920c9d0bb3d8d8f731d2e13a9 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
int K = in.nextInt();
int[][] dp = new int[N + 1][K + 1];
for (int i = 1; i <= N; i++) {
char[] str = in.next().toCharArray();
int[] skip = new int[501];
Arrays.fill(skip, M + 1);
ArrayList<Integer> times = new ArrayList<>();
for (int j = 0; j < M; j++) {
if (str[j] == '1') {
times.add(j);
}
}
for (int pref = 0; pref < times.size(); pref++) {
for (int suf = times.size() - 1; suf >= pref; suf--) {
skip[pref + times.size() - 1 - suf] = Math.min(skip[pref + times.size() - 1 - suf], times.get(suf) - times.get(pref) + 1);
}
}
skip[times.size()] = 0;
for (int alrd = 0; alrd <= K; alrd++) {
dp[i][alrd] = dp[i - 1][alrd] + skip[0];
for (int j = 1; j <= alrd; j++) {
dp[i][alrd] = Math.min(dp[i][alrd], dp[i - 1][alrd - j] + skip[j]);
}
}
}
out.println(dp[N][K]);
}
}
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 | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 7d3e02537cc01628df7b6e5989390511 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 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.Arrays;
import java.util.StringTokenizer;
public class D {
static final int INF = (int)1e9;
static int [][] min, memo;
static int dp(int idx, int skp){
if(idx == min.length)
return 0;
if(memo[idx][skp] != -1)
return memo[idx][skp];
int ans = INF;
for (int i = skp; i >= 0; i--) {
ans = Math.min(ans, min[idx][i] + dp(idx+1, skp-i));
}
return memo[idx][skp] = ans;
}
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(), k = sc.nextInt();
char [][] c = new char[n][m];
for (int i = 0; i < c.length; i++) {
c[i] = sc.next().toCharArray();
}
min = new int[n][Math.max(m, k)+1];
memo = new int[n+1][k+1];
for(int []i:min)
Arrays.fill(i, m);
for(int []i:memo)
Arrays.fill(i, -1);
for (int i = 0; i < c.length; i++) {
int les = 0;
for (int j = 0; j < c[i].length; j++) {
les += c[i][j] - '0';
}
for (int j = 0; j <= les; j++) {
int s = 0, e = 0, ans = m;
while(s < c[i].length && c[i][s] == '0') s++;
e = s;
for (int l = 0; l < j-1; l++){
e++;
while(e < c[i].length && c[i][e] == '0') e++;
}
if(j == 0) e--;
ans = Math.max(0, e-s+1);
while(true){
e++;
while(e < c[i].length && c[i][e] == '0') e++;
if(e >= m)
break;
s++;
while(s < c[i].length && c[i][s] == '0') s++;
ans = Math.min(ans, Math.max(0, e-s+1));
}
min[i][les-j] = ans;
}
}
// for(int []i:min)
// out.println(Arrays.toString(i));
out.println(dp(0, k));
out.flush();
out.close();
}
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 | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 95211e8a920df6e2b54e34530a355d94 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DTimetable solver = new DTimetable();
solver.solve(1, in, out);
out.close();
}
static class DTimetable {
private int n;
private int m;
private int K;
private int[][] arr;
private int[][] min;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
K = in.nextInt();
arr = new int[n + 1][m + 1];
min = new int[n + 1][501];
for (int i = 1; i <= n; i++) {
String str = in.nextLine();
for (int j = 1; j <= m; j++) {
arr[i][j] = str.charAt(j - 1) - 48;
if (arr[i][j] == 1) arr[i][0]++;
}
}
for (int i = 0; i <= n; i++) Arrays.fill(min[i], Integer.MAX_VALUE);
for (int i = 1; i <= n; i++) {
min[i][arr[i][0]] = 0;
for (int j = 1; j <= m; j++) {
int count = 0;
for (int k = j; k <= m; k++) {
if (arr[i][k] == 1) count++;
min[i][arr[i][0] - count] = Math.min(min[i][arr[i][0] - count], k - j + 1);
}
}
for (int j = 1; j <= 500; j++) {
min[i][j] = Math.min(min[i][j], min[i][j - 1]);
}
// int mark1, mark2;
// if (arr[i][1] == 1) mark1 = 1;
// else mark1 = next[i][1][1];
//
// if (arr[i][m] == 1) mark2 = m;
// else mark2 = next[i][m][0];
// if (mark2 == 0) continue;
// for (int k=0; k<=K; k++) {
//// Arrays.fill(temp, -1);
// hm.clear();
// min[i][k] = minSolve(i, mark1, mark2, k);
// }
// for (int k=0; k<=K; k++) {
// min[i][k] = mark2-mark1+1;
// if (mark1 == mark2) break;
// if (mark2-next[i][mark2][0] > next[i][mark1][1]-mark1) mark2 = next[i][mark2][0];
// else mark1 = next[i][mark1][1];
// }
}
// out.println("----------------------------");
// for (int i=0; i<=n; i++) {
// for (int j=0; j<=m; j++) out.printsc(next[i][j][0]);
// out.println();
// }
// out.println("----------------------------");
// for (int i=0; i<=n; i++) {
// for (int j=0; j<=m; j++) out.printsc(next[i][j][1]);
// out.println();
// }
// out.println("----------------------------");
// for (int i=0; i<=n; i++) {
// out.printsc(min[i][0], min[i][1], min[i][2], min[i][3], min[i][4], min[i][5], min[i][6], min[i][7], min[i][8]);
// out.println();
// }
int[][] dp = new int[n + 1][K + 1];
for (int j = 0; j <= K; j++) {
dp[1][j] = min[1][j];
if (min[1][j] == 0) break;
}
for (int i = 2; i <= n; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
for (int i = 2; i <= n; i++) {
for (int j = 0; j <= K; j++) {
for (int k = 0; k <= j; k++) {
// if (dp[i][j] == 0) dp[i][j] = dp[i-1][j-k] + min[i][k];
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - k] + min[i][k]);
// if (min[i][k] == 0) break;
}
}
}
out.println(dp[n][K]);
out.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public InputReader(FileInputStream file) {
this.stream = file;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = (res << 3) + (res << 1) + c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
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();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static class OutputWriter {
private final PrintWriter writer;
private ArrayList<String> res = new ArrayList<>();
private StringBuilder sb = new StringBuilder("");
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
sb.append(objects[i]);
}
res.add(sb.toString());
sb = new StringBuilder("");
}
public void close() {
// writer.flush();
writer.close();
}
public void flush() {
for (String str : res) writer.printf("%s\n", str);
res.clear();
sb = new StringBuilder("");
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 693449947af55386c1df18ec47f6e0e5 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 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 Main {
static final int UNCALC = -1, INF = (int) 1e9, max = 501;
static int n, cost[][], memo[][];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int m = sc.nextInt(), k = sc.nextInt();
cost = new int[n][max];
for (int i = 0; i < n; i++) {
char[] cur = sc.next().toCharArray();
int tot = 0;
for (char c : cur)
if (c == '1') tot++;
Arrays.fill(cost[i], m);
cost[i][tot] = 0;
for (int start = 0; start < m; start++) {
int cnt = 0;
for (int end = start; end < m; end++) {
if (cur[end] == '1') cnt++;
int skip = tot - cnt;
cost[i][skip] = Math.min(cost[i][skip], end - start + 1);
}
}
}
memo = new int[k + 1][n];
for (int[] a : memo)
Arrays.fill(a, UNCALC);
out.println(dp(k, 0));
out.flush();
out.close();
}
static int dp(int rem, int i) {
if (i == n) return 0;
if (memo[rem][i] != UNCALC) return memo[rem][i];
int min = INF;
for (int skip = 0; skip <= rem; skip++)
min = Math.min(min, cost[i][skip] + dp(rem - skip, i + 1));
return memo[rem][i] = min;
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | e9c0508d8782dda19e41ba0bb709098e | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class D {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
// int[] a = new int[n];
// for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[][] classes = new int[n][m];
for(int i=0; i<n; i++) {
String s = bf.readLine();
for(int j=0; j<m; j++) {
if(s.charAt(j) == '0') classes[i][j] = 0;
else classes[i][j] = 1;
}
}
int[][] min_stay = new int[n][k+1];
for(int i=0; i<n; i++) {
int count = 0;
for(int x : classes[i]) if(x == 1) count++;
for(int skip = 0; skip <= k; skip++) {
if(skip >= count) min_stay[i][skip] = 0;
else {
int[] first_index = new int[skip+1];
int[] last_index = new int[skip+1];
int skip_count = 0;
for(int j=0; j<m; j++) {
if(classes[i][j] == 1) {
first_index[skip_count] = j;
skip_count++;
if(skip_count >= skip+1) break;
}
}
skip_count = 0;
for(int j=m-1; j>=0; j--) {
if(classes[i][j] == 1) {
last_index[skip_count] = j;
skip_count++;
if(skip_count >= skip+1) break;
}
}
// System.out.println(Arrays.toString(first_index));
// System.out.println(Arrays.toString(last_index));
int min = Integer.MAX_VALUE;
for(int j=0; j<=skip; j++) if(last_index[j] - first_index[skip-j] + 1 < min) min = last_index[j] - first_index[skip-j] + 1;
min_stay[i][skip] = min;
}
}
}
int[][] min_total_stay = new int[n][k+1];
for(int i=0; i<n; i++) {
for(int j=0; j<=k; j++) {
int min = Integer.MAX_VALUE;
for(int a=0; a<=j; a++) {
int val = 0;
if(i > 0) val += min_total_stay[i-1][a];
val += min_stay[i][j-a];
if(val < min) min = val;
}
min_total_stay[i][j] = min;
}
}
System.out.println(min_total_stay[n-1][k]);
// out.close(); System.exit(0);
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | dc4dc70bdb7c7cc2d3a4cd0998e7f89e | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private static ArrayList<ArrayList<Integer>> classes = new ArrayList<ArrayList<Integer>>();
private static ArrayList<ArrayList<Integer>> gaps = new ArrayList<ArrayList<Integer>>();
private static ArrayList<ArrayList<Integer>> prefixes = new ArrayList<ArrayList<Integer>>();
private static int[][] matrix = new int[502][502];
private static int[][] dp = new int[502][502];
private static int N, M, K;
private static final int INF = 1 << 29;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
for (int i = 0; i < N; i++) {
classes.add(new ArrayList<Integer>());
gaps.add(new ArrayList<Integer>());
prefixes.add(new ArrayList<Integer>());
}
for (int i = 0; i < N; i++) {
String str = f.readLine();
for (int k = 0; k < M; k++) {
if (str.substring(k, k + 1).equals("1")) {
classes.get(i).add(k);
}
}
}
for (int i = 0; i < N; i++) {
for (int k = 0; k < classes.get(i).size() - 1; k++) {
gaps.get(i).add(classes.get(i).get(k + 1) - classes.get(i).get(k));
}
}
for (int i = 0; i < N; i++) {
prefixes.get(i).add(0);
for (int k = 0; k < gaps.get(i).size(); k++) {
prefixes.get(i).add(prefixes.get(i).get(k) + gaps.get(i).get(k));
}
}
for (int i = 0; i < 502; i++) {
Arrays.fill(matrix[i], Integer.MAX_VALUE);
Arrays.fill(dp[i], -1);
}
for (int i = 0; i < N; i++) {
init(i);
}
for (int i = 0; i < 502; i++) {
for (int k = 0; k < 502; k++) {
if (matrix[i][k] == Integer.MAX_VALUE) {
matrix[i][k] = 0;
}
}
}
System.out.println(dfs(0, 0));
}
public static int dfs(int day, int count) {
if (count > K) {
return INF;
}
if (day == N)
return 0;
if (dp[day][count] != -1) {
return dp[day][count];
}
int result = INF;
for (int i = 0; i <= classes.get(day).size(); i++) {
result = Math.min(result, dfs(day + 1, count + i) + matrix[day][i]);
}
dp[day][count] = result;
return result;
}
public static void init(int day) {
for (int left = 0; left < classes.get(day).size(); left++) {
for (int right = left; right < classes.get(day).size(); right++) {
int skip = classes.get(day).size() - (right - left) - 1;
int value = query(day, left, right);
matrix[day][skip] = Math.min(matrix[day][skip], value);
}
}
}
public static int query(int day, int left, int right) {
return prefixes.get(day).get(right) - prefixes.get(day).get(left) + 1;
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 8ade94999ef3a11c0c3de03cd5dc1d1f | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
public class _946D {
/**********************************************************************************************
* DEBUG *
* - Obvious dp would be try to remember state of the board but that's too slow because
* - there are m^2 states for each day, there are n days => there are m^2n for the whole board
* - each check cost m calculations for the hashcode and equals
* -
**********************************************************************************************/
private final static boolean DEBUG = false;
private final static String[] DEBUG_INPUT = {
"2 5 1\n" +
"01001\n" +
"10110",
"2 5 0\n" +
"01001\n" +
"10110",
"3 4 0\n" +
"0000\n" +
"0000\n" +
"0000",
"3 4 12\n" +
"1111\n" +
"1111\n" +
"1111",
"4 4 7\n" +
"1001\n" +
"1001\n" +
"1001\n" +
"1001\n"
};
// static {
// StringBuilder sb = new StringBuilder();
// Random random = new Random();
// sb.append("500 500 500\n");
// for (int i = 0; i < 500; i++) {
// StringBuilder sbRow = new StringBuilder();
// for (int j = 0; j < 500; j++) {
// sbRow.append(random.nextInt(10) % 2);
// }
// sb.append("\n");
// sb.append(sbRow.toString());
// }
// DEBUG_INPUT[0] = sb.toString();
// }
/**********************************************************************************************
* MAIN *
**********************************************************************************************/
// input
// 2 5 1
// 01001
// 10110
// output
// 5
// 2 8 2
// 10100011
// 10011100
// 4/8 4/6
// - graph
// - dp
// - state: remaining days, the remaining timetable: 500 x (left, right)
private static class Solver {
private static final int MIN = -999_999_999;
private static final int MAX = 999_999_999;
public void solve(Reader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
char[][] a = new char[n][];
for (int i = 0; i < n; i++) a[i] = in.nextWord().toCharArray();
out.print(solve(n, m, k, a));
}
private int solve(int n, int m, int k, char[][] a) {
int[] oneCount = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == '1') oneCount[i]++;
}
}
// if we skip j first 1(s) in i-th row, where would the next 1 be
int[][][] skipTable = new int[n][m+1][2]; // 0: left -> right, 1: right -> left
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
skipTable[i][j][0] = skipTable[i][j][1] = -1;
}
}
for (int i = 0; i < n; i++) {
int countLeft = 0;
int countRight = 0;
for (int j = 0; j < m; j++) {
if (a[i][j] == '1') {
countLeft++;
skipTable[i][countLeft-1][0] = j;
}
if (a[i][m-1-j] == '1') {
countRight++;
skipTable[i][countRight-1][1] = m-1-j;
}
}
}
int[][] eachDay = new int[n][k+1]; // [i][j] is minimum hours of day i if skip j lessons
for (int[] i : eachDay) Arrays.fill(i, MAX);
for (int i = 0; i < n; i++) {
int skippable = Math.min(oneCount[i], k);
for (int j = 0; j <= skippable; j++) {
int res = MAX;
for (int l = 0; l <= j; l++) {
int skipLeft = l;
int skipRight = j - skipLeft;
int first1Left = skipTable[i][skipLeft][0];
int first1Right = skipTable[i][skipRight][1];
if (first1Left == -1 || first1Right == -1 || first1Left > first1Right) {
res = 0;
break;
} else {
res = Math.min(res, first1Right - first1Left + 1);
}
}
eachDay[i][j] = res;
}
}
int[][] dp = new int[n][k+1]; // [i][j] is minimum hours need to spend if skip j lessons in first i days
for (int i = 0; i < n; i++) {
int skippable = Math.min(oneCount[i], k);
for (int j = 0; j <= k; j++) { // if we skip j lessons in first i days
int res = MAX;
int skippable2 = Math.min(j, skippable);
for (int l = 0; l <= skippable2; l++) { // if we skip l lessons in i-th day
int prev = i == 0 ? 0 : dp[i-1][j-l];
res = Math.min(res, prev + eachDay[i][l]);
}
dp[i][j] = res;
}
}
return dp[n-1][k];
}
// private int solve(int n, int m, int k, char[][] a) {
// int[][][] nextTable = new int[n][m][2]; // 0: left -> right, 1: right -> left
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// nextTable[i][j][0] = nextTable[i][j][1] = -1;
// }
// }
// int[][] intervals = new int[n][2]; // 0: left, 1: right
// for (int[] i :intervals) {
// i[0] = 0;
// i[1] = -1;
// }
// for (int i = 0; i < n; i++) {
// int prevOneL2RIdx = -1;
// int prevOneR2LIdx = m;
// for (int j = 0; j < m; j++) {
// if (a[i][j] == '1') {
// if (prevOneL2RIdx != -1) nextTable[i][prevOneL2RIdx][0] = j;
// prevOneL2RIdx = j;
// }
// if (a[i][m-1-j] == '1') {
// if (prevOneR2LIdx != m) nextTable[i][prevOneR2LIdx][1] = m-1-j;
// prevOneR2LIdx = m-1-j;
// }
// }
// for (int j = 0; j < m; j++) {
// if (a[i][j] == '1') {
// intervals[i][0] = j;
// break;
// }
// }
// for (int j = m-1; j >=0; j--) {
// if (a[i][j] == '1') {
// intervals[i][1] = j;
// break;
// }
// }
// }
// State origin = new State(intervals, k);
// Map<State, Integer> memo = new HashMap<>();
// return go(memo, nextTable, origin);
// }
//
// private int go(Map<State, Integer> memo, int[][][] table, State state) {
// Integer cache = memo.get(state);
// if (cache != null) return cache;
//
// if (state.remainDays == 0) return state.calculateCost();
//
// int res = Integer.MAX_VALUE;
// for (int i = 0; i < state.intervals.length; i++) {
// State delete = state.delete(table, i, 0);
// if (delete != null) res = Math.min(res, go(memo, table, delete));
// delete = state.delete(table, i, 1);
// if (delete != null) res = Math.min(res, go(memo, table, delete));
// }
// memo.put(state, res);
// return res == Integer.MAX_VALUE ? 0 : res;
// }
//
// private static class State {
// int[][] intervals;
// int remainDays;
//
// public State(State that) {
// this(that.intervals, that.remainDays);
// }
//
// public State(int[][] intervals, int remainDays) {
// this.remainDays = remainDays;
// int n = intervals.length;
// int m = intervals[0].length;
// this.intervals = new int[n][m];
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// this.intervals[i][j] = intervals[i][j];
// }
// }
// }
//
// private int calculateCost() {
// int cost = 0;
// for (int[] i : intervals) {
// int todayCost = i[1] < i[0] ? 0 : i[1] - i[0] + 1;
// cost += todayCost;
// }
// return cost;
// }
//
// private State delete(int[][][] table, int day, int side) { // side: 0 = left, 1 = right
// if (this.intervals[day][0] == -1 || this.intervals[day][1] == -1) return null;
// if (this.intervals[day][0] > this.intervals[day][1]) return null;
// int prev = this.intervals[day][side];
// State res = new State(this);
// res.intervals[day][side] = table[day][prev][side];
// res.remainDays--;
// return res;
// }
//
// @Override
// public int hashCode() {
// return 31 * remainDays + Arrays.deepHashCode(intervals);
// }
//
// @Override
// public boolean equals(Object obj) {
// State that = (State) obj;
// return Arrays.deepEquals(this.intervals, that.intervals) && this.remainDays == that.remainDays;
// }
// }
}
/**********************************************************************************************
* TEMPLATE *
**********************************************************************************************/
public static void main(String[] args) throws IOException {
PrintWriter out = null;
Reader in;
if (DEBUG) {
for (String s : DEBUG_INPUT) {
in = new Reader(new ByteArrayInputStream(s.getBytes()));
out = new PrintWriter(System.out);
out.println("===>>> INPUT");
out.println(s + "\n\n");
out.println("===>>> OUTPUT");
long start = System.currentTimeMillis();
new Solver().solve(in, out);
long end = System.currentTimeMillis();
out.println("\n");
out.println("===========");
out.println("Took: " + (end - start) + "ms");
out.println("====================================================================");
out.println();
out.println();
out.flush();
}
} else {
in = new Reader(System.in);
out = new PrintWriter(System.out);
new Solver().solve(in, out);
}
if (out != null) out.flush();
}
/** Reader **/
private static class Reader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
private String nextWord() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextWord());
}
private long nextLong() throws IOException {
return Long.parseLong(nextWord());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextWord());
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | c7c6eaa711e98edca39f531c5acd8e54 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | //package educational.round39;
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 D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni();
char[][] map = nm(n,m);
int[] dp = new int[K+1];
Arrays.fill(dp, 99999999);
dp[0] = 0;
for(char[] row : map){
int[] len = new int[m+1];
Arrays.fill(len, 99999999);
len[0] = 0;
int none = 0;
for(int i = 0;i < m;i++){
if(row[i] == '1'){
int one = 0;
for(int j = i;j < m;j++){
if(row[j] == '1'){
one++;
len[one] = Math.min(len[one], j-i+1);
}
}
none = Math.max(none, one);
}
}
int[] ndp = new int[K+1];
Arrays.fill(ndp, 99999999);
for(int i = 0;i <= K;i++){
for(int j = 0;i+j <= K && j <= none;j++){
ndp[i+j] = Math.min(ndp[i+j],
dp[i] + len[none-j]);
}
}
dp = ndp;
}
int ans = 99999999;
for(int i = 0;i <= K;i++){
ans = Math.min(ans, dp[i]);
}
out.println(ans);
}
void run() throws Exception
{
// int n = 500, m = 99999;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(5 + " ");
// sb.append(500 + " ");
// for (int i = 0; i < n; i++) {
// for(int j = 0;j < 5;j++){
// sb.append(gen.nextInt(2));
// }
// sb.append("\n");
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | da5c7befb70c574f112eb99bc427c7fa | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
public class _946D {
/**********************************************************************************************
* DEBUG *
* - Obvious dp would be try to remember state of the board but that's too slow because
* - there are m^2 states for each day, there are n days => there are m^2n for the whole board
* - each check cost m calculations for the hashcode and equals
* -
**********************************************************************************************/
private final static boolean DEBUG = false;
private final static String[] DEBUG_INPUT = {
"2 5 1\n" +
"01001\n" +
"10110",
"2 5 0\n" +
"01001\n" +
"10110",
"3 4 0\n" +
"0000\n" +
"0000\n" +
"0000",
"3 4 12\n" +
"1111\n" +
"1111\n" +
"1111",
"4 4 7\n" +
"1001\n" +
"1001\n" +
"1001\n" +
"1001\n"
};
// static {
// StringBuilder sb = new StringBuilder();
// Random random = new Random();
// sb.append("500 500 500\n");
// for (int i = 0; i < 500; i++) {
// StringBuilder sbRow = new StringBuilder();
// for (int j = 0; j < 500; j++) {
// sbRow.append(random.nextInt(10) % 2);
// }
// sb.append("\n");
// sb.append(sbRow.toString());
// }
// DEBUG_INPUT[0] = sb.toString();
// }
/**********************************************************************************************
* MAIN *
**********************************************************************************************/
// input
// 2 5 1
// 01001
// 10110
// output
// 5
// 2 8 2
// 10100011
// 10011100
// 4/8 4/6
// - graph
// - dp
// - state: remaining days, the remaining timetable: 500 x (left, right)
private static class Solver {
private static final int MIN = -999_999_999;
private static final int MAX = 999_999_999;
public void solve(Reader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
char[][] a = new char[n][];
for (int i = 0; i < n; i++) a[i] = in.nextWord().toCharArray();
out.print(solve(n, m, k, a));
}
private int solve(int n, int m, int k, char[][] a) {
int[] oneCount = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == '1') oneCount[i]++;
}
}
// if we skip j first 1(s) in i-th row, where would the next 1 be
// int[][][] skipTable = new int[n][m+1][2]; // 0: left -> right, 1: right -> left
// for (int i = 0; i < n; i++) {
// for (int j = 0; j <= m; j++) {
// skipTable[i][j][0] = skipTable[i][j][1] = -1;
// }
// }
// for (int i = 0; i < n; i++) {
// int countLeft = 0;
// int countRight = 0;
// for (int j = 0; j < m; j++) {
// if (a[i][j] == '1') {
// countLeft++;
// skipTable[i][countLeft-1][0] = j;
// }
// if (a[i][m-1-j] == '1') {
// countRight++;
// skipTable[i][countRight-1][1] = m-1-j;
// }
// }
// }
int[][] eachDay = new int[n][k+1]; // [i][j] is minimum hours of day i if skip j lessons
for (int[] i : eachDay) Arrays.fill(i, MAX);
for (int i = 0; i < n; i++) {
if (oneCount[i] <= k) eachDay[i][oneCount[i]] = 0; // skip all
for (int j = 0; j < m; j++) {
if (a[i][j] == '1') {
int count = 0;
for (int l = j; l < m; l++) {
if (a[i][l] == '1') {
count++;
int skip = oneCount[i] - count;
if (skip > k) continue;
int len = l - j + 1;
eachDay[i][skip] = Math.min(eachDay[i][skip], len);
}
}
}
}
}
// for (int i = 0; i < n; i++) {
// int skippable = Math.min(oneCount[i], k);
// for (int j = 0; j <= skippable; j++) {
// int res = MAX;
// for (int l = 0; l <= j; l++) {
// int skipLeft = l;
// int skipRight = j - skipLeft;
// int first1Left = skipTable[i][skipLeft][0];
// int first1Right = skipTable[i][skipRight][1];
// if (first1Left == -1 || first1Right == -1 || first1Left > first1Right) {
// res = 0;
// break;
// } else {
// res = Math.min(res, first1Right - first1Left + 1);
// }
// }
// eachDay[i][j] = res;
// }
// }
int[][] dp = new int[n][k+1]; // [i][j] is minimum hours need to spend if skip j lessons in first i days
for (int i = 0; i < n; i++) {
int skippable = Math.min(oneCount[i], k);
for (int j = 0; j <= k; j++) { // if we skip j lessons in first i days
int res = MAX;
int skippable2 = Math.min(j, skippable);
for (int l = 0; l <= skippable2; l++) { // if we skip l lessons in i-th day
int prev = i == 0 ? 0 : dp[i-1][j-l];
res = Math.min(res, prev + eachDay[i][l]);
}
dp[i][j] = res;
}
}
return dp[n-1][k];
}
}
/**********************************************************************************************
* TEMPLATE *
**********************************************************************************************/
public static void main(String[] args) throws IOException {
PrintWriter out = null;
Reader in;
if (DEBUG) {
for (String s : DEBUG_INPUT) {
in = new Reader(new ByteArrayInputStream(s.getBytes()));
out = new PrintWriter(System.out);
out.println("===>>> INPUT");
out.println(s + "\n\n");
out.println("===>>> OUTPUT");
long start = System.currentTimeMillis();
new Solver().solve(in, out);
long end = System.currentTimeMillis();
out.println("\n");
out.println("===========");
out.println("Took: " + (end - start) + "ms");
out.println("====================================================================");
out.println();
out.println();
out.flush();
}
} else {
in = new Reader(System.in);
out = new PrintWriter(System.out);
new Solver().solve(in, out);
}
if (out != null) out.flush();
}
/** Reader **/
private static class Reader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
private String nextWord() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextWord());
}
private long nextLong() throws IOException {
return Long.parseLong(nextWord());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextWord());
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 37c1f108912f450d7f588ebadf729f0b | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Collection;
import java.io.IOException;
import java.util.OptionalInt;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.stream.Stream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyScan in = new MyScan(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, MyScan in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[][] wh = new int[n][k + 1];
for (int i = 0; i < n; i++) {
String l = in.next();
ArrayList<Integer> tt = new ArrayList<>();
for (int t = 0; t < m; t++) {
if (l.charAt(t) == '1') {
tt.add(t);
}
}
int[] cur = tt.stream().mapToInt(sss -> sss).toArray();
Arrays.fill(wh[i], Integer.MAX_VALUE);
for (int s = 0; s < cur.length; s++) {
for (int x = s; x < cur.length; x++) {
int len = x - s + 1;
int kkk = cur.length - len;
if (kkk <= k) {
wh[i][kkk] = Math.min(wh[i][kkk], cur[x] - cur[s] + 1);
}
}
}
for (int s = 0; s < wh[i].length; s++) {
if (wh[i][s] == Integer.MAX_VALUE) {
wh[i][s] = 0;
}
}
}
int[] ans = wh[0];
for (int i = 1; i < n; i++) {
ans = m(ans, wh[i], k + 1);
}
out.println(Arrays.stream(ans).min().getAsInt());
}
private int[] m(int[] ans, int[] ints, int k) {
int[] res = new int[k];
Arrays.fill(res, Integer.MAX_VALUE);
for (int s = 0; s < ans.length; s++) {
for (int t = 0; t < ans.length; t++) {
if (s + t >= res.length) break;
res[s + t] = Math.min(res[s + t], ans[s] + ints[t]);
}
}
return res;
}
}
static class MyScan {
BufferedReader br;
StringTokenizer st;
MyScan(BufferedReader br) {
this.br = br;
}
public MyScan(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
public void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
findToken();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | d1c38576cb369466f95644a81572df1f | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author rizhiy
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
char[][] ch = new char[n][m];
for (int i = 0; i < n; i++) {
ch[i] = in.next().toCharArray();
}
ArrayList<Integer> p[] = new ArrayList[n];
for (int i = 0; i < n; i++) {
p[i] = new ArrayList<>();
for (int j = 0; j < m; j++) {
if (ch[i][j] == '1') {
p[i].add(j);
}
}
}
int[][] d = new int[n][k + 1];
for (int i = 0; i < n; i++) {
if (p[i].size() > 0) {
d[i][0] = p[i].get(p[i].size() - 1) - p[i].get(0) + 1;
for (int j = 1; j <= Math.min(k, p[i].size() - 1); j++) {
int min = Integer.MAX_VALUE;
for (int u = 0; u <= j; u++) {
int nu = j - u;
min = Math.min(min, p[i].get(p[i].size() - 1 - nu) - p[i].get(u));
}
d[i][j] = min + 1;
}
}
}
if (k == 0) {
int answ = 0;
for (int i = 0; i < n; i++) {
answ += d[i][0];
}
out.println(answ);
return;
}
long[][] d2 = new long[n][k + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
d2[i][j] = Integer.MAX_VALUE;
}
}
d2[0][0] = d[0][0];
for (int i = 1; i < n; i++) {
d2[i][0] = d[i][0] + d2[i - 1][0];
}
for (int j = 0; j <= k; j++) {
d2[0][j] = d[0][j];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= k; j++) {
for (int u = 0; u <= j; u++) {
d2[i][j] = Math.min(d2[i][j], d2[i - 1][j - u] + d[i][u]);
}
}
}
out.println(d2[n - 1][k]);
}
}
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 | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 9f1a1d55e0c5e6f719cc3c5a8b37684b | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.*;
import java.util.*;
public class CF946D {
static void solve(int[] dp, char[] cc, int n, int k) {
int n1 = 0;
for (int i = 0; i < n; i++)
if (cc[i] == '1')
n1++;
if (n1 == 0)
return;
int[] ii = new int[n1];
n1 = 0;
for (int i = 0; i < n; i++)
if (cc[i] == '1')
ii[n1++] = i;
int span = ii[n1 - 1] - ii[0] + 1;
for (int l = 0; l <= k; l++)
dp[l] = span;
for (int i = 0; i < n1; i++)
for (int j = i; j < n1; j++) {
int l = i + n1 - 1 - j;
if (l <= k) {
int span_ = ii[j] - ii[i] + 1;
dp[l] = Math.min(dp[l], span_);
}
}
for (int l = n1; l <= k; l++)
dp[l] = 0;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
char[][] cc = new char[n][m];
for (int i = 0; i < n; i++)
br.readLine().getChars(0, m, cc[i], 0);
int[][] dp = new int[n][1 + k];
for (int i = 0; i < n; i++)
solve(dp[i], cc[i], m, k);
int[][] dq = new int[n][1 + k];
for (int l = 0; l <= k; l++)
dq[0][l] = dp[0][l];
for (int i = 1; i < n; i++)
for (int l = 0; l <= k; l++) {
int x = Integer.MAX_VALUE;
for (int l_ = 0; l_ <= l; l_++) {
int y = dp[i][l_] + dq[i - 1][l - l_];
if (x > y)
x = y;
}
dq[i][l] = x;
}
System.out.println(dq[n - 1][k]);
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | bd06ee0d9cf2cba215cb343909ae5e26 | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
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);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
String []s = new String[n+1];
int[][]time = new int[n+1][k+2];
int mx = 2600;
int[]one = new int[n+1];
for(int i=1;i<=n;i++){
s[i]= in.next();
int c = 0;
for(int j=0;j<m;j++){
if (s[i].charAt(j)=='1'){
c++;
}
}
one[i]=c;
}
for(int i=1;i<=n;i++){
int last=-1;
for(int j=0;j<=k;j++){
int mn = mx;
int takeClass = one[i]-j;
if(takeClass<=0){
mn=0;
}
else {
int run = -1;
int take=0;
for(int i1=0;i1<m;i1++){
if(s[i].charAt(i1)=='1'){
take++;
}
if(take==takeClass){
run++;
while (s[i].charAt(run)!='1'){
run++;
}
take--;
mn=Math.min(mn,i1-(run-1));
}
}
}
int add = m-mn;
for(int i1=last+1;i1<=k;i1++){
time[i][i1] = Math.max(time[i-1][i1],time[i][i1]);
time[i][i1] = Math.max(time[i][i1],add+time[i-1][i1-j]);
}
last++;
}
}
System.out.println(n*m-time[n][k]);
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | d37717d0dc4e98c0a157a604eff5012d | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes |
import java.util.*;
import java.io.*;
public class Timetable_946D {
static void go() {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
List<List<Integer>> dmin = new ArrayList<>();
for(int i = 0; i < n; i++) {
List<Integer> idx = new ArrayList<>();
char[] str = in.nextString().toCharArray();
for(int j = 0; j < m; j++) {
if (str[j] == '1') idx.add(j);
}
if (idx.size() == 0) continue;
List<Integer> dd = new ArrayList<>();
for(int diff = 0; diff < idx.size(); diff++) {
int min = Integer.MAX_VALUE;
for(int s = 0, e = idx.size()-1-diff; e < idx.size(); s++, e++)
min = Math.min(min, idx.get(e) - idx.get(s) + 1);
dd.add(min);
}
dd.add(0);
dmin.add(dd);
}
n = dmin.size();
int[][] dp = new int[k+1][n+1];
for(int i = 0; i <= k; i++) {
for(int j = 1; j <= n; j++) {
List<Integer> day = dmin.get(j-1);
dp[i][j] = dp[i][j-1] + day.get(0);
for(int d = 1; d < Math.min(i+1, day.size()); d++) {
dp[i][j] = Math.min(dp[i][j], dp[i - d][j-1] + day.get(d));
}
}
}
out.println(dp[k][n]);
}
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
go();
out.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 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[] nextIntArray(int len) {
int[] ret = new int[len];
for (int i = 0; i < len; i++)
ret[i] = nextInt();
return ret;
}
public long[] nextLongArray(int len) {
long[] ret = new long[len];
for (int i = 0; i < len; i++)
ret[i] = nextLong();
return ret;
}
public int nextInt() {
return (int) nextLong();
}
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 nextLine() {
StringBuilder sb = new StringBuilder(1024);
int c = read();
while (!(c == '\n' || c == '\r' || c == -1)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
public char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder sb = new StringBuilder(1024);
do {
sb.append((char) c);
c = read();
} while (!isSpaceChar(c));
return sb.toString();
}
public char[] nextCharArray(int n) {
char[] ca = new char[n];
for (int i = 0; i < n; i++) {
int c = read();
while (isSpaceChar(c))
c = read();
ca[i] = (char) c;
}
return ca;
}
public static boolean isSpaceChar(int c) {
switch (c) {
case -1:
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
}
} | Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | 9d9e18d48c012920fb4a5a05910ec13c | train_001.jsonl | 1520348700 | Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends jβ-βiβ+β1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int[][] dp;
char[][] time;
int n;
int m;
int k;
int[][] timeUsed;
int[][] sum;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.readInt();
m = in.readInt();
k = in.readInt();
dp = new int[n][k + 1];
for (int[] a : dp) Arrays.fill(a, -1);
time = new char[n][];
timeUsed = new int[n][501];
sum = new int[n][501];
for (int i = 0; i < n; i++) {
time[i] = in.readString().toCharArray();
sum[i][0] = time[i][0] - '0';
int max = 0, min = m - 1;
for (int j = 0; j < m; j++) {
if (j > 0) sum[i][j] = sum[i][j - 1] + time[i][j] - '0';
if (time[i][j] == '1') {
max = Math.max(max, j);
min = Math.min(min, j);
}
}
for (int j = 0; j < timeUsed[i].length; j++) timeUsed[i][j] = Integer.MAX_VALUE;
timeUsed[i][0] = Math.max(0, max - min + 1);
timeUsed[i][sum[i][m - 1]] = 0;
for (int x = 0; x < m; x++) {
for (int y = x; y < m; y++) {
if (time[i][x] == '0' || time[i][y] == '0') continue;
int skip = sum[i][m - 1] - (sum[i][y] - sum[i][x] + time[i][x] - '0');
timeUsed[i][skip] = Math.min(timeUsed[i][skip], y - x + 1);
}
}
}
out.println(go(0, k));
}
int go(int day, int canSkip) {
if (day >= n) return 0;
if (dp[day][canSkip] >= 0) return dp[day][canSkip];
dp[day][canSkip] = timeUsed[day][0] + go(day + 1, canSkip);
for (int i = 1; i <= canSkip; i++) {
if (timeUsed[day][i] == Integer.MAX_VALUE) continue;
dp[day][canSkip] = Math.min(dp[day][canSkip], timeUsed[day][i] + go(day + 1, canSkip - i));
}
return dp[day][canSkip];
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 5 1\n01001\n10110", "2 5 0\n01001\n10110"] | 2 seconds | ["5", "8"] | NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Java 8 | standard input | [
"dp"
] | cf5650c13ce0404d2df10fa3196d7923 | The first line contains three integers n, m and k (1ββ€βn,βmββ€β500, 0ββ€βkββ€β500) β the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson). | 1,800 | Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons. | standard output | |
PASSED | f152d7f71110a0c563a41abb42ed124e | train_001.jsonl | 1495958700 | The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).What is the minimum cost of preparation and printing? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt();
int [] a = new int[n], b = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int N = n + 2;
List<Edge> adjList [] = new List[N];
for (int i = 0; i < N; i++) adjList[i] = new ArrayList<>();
for (int i = 0; i < n; i++) addEdge(adjList, 0, i + 1, 1, a[i]);
for (int i = 0; i < n; i++) {
addEdge(adjList, i + 1, N - 1, 1, b[i]);
if (i != n - 1) addEdge(adjList, i + 1, i + 2, (int)1e7, 0);
}
out.println(minCostFlow(adjList, 0, N - 1, k)[1]);
out.flush();
out.close();
}
static class Edge {
int to, f, cap, cost, rev;
Edge(int to, int cap, int cost, int rev) {
this.to = to;
this.cap = cap;
this.cost = cost;
this.rev = rev;
}
}
public static void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) {
graph[s].add(new Edge(t, cap, cost, graph[t].size()));
graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1));
}
static void bellmanFord(List<Edge>[] graph, int s, int[] dist) {
int n = graph.length;
Arrays.fill(dist, Integer.MAX_VALUE);
dist[s] = 0;
boolean[] inqueue = new boolean[n];
int[] q = new int[n];
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % n != 0; qh++) {
int u = q[qh % n];
inqueue[u] = false;
for (int i = 0; i < graph[u].size(); i++) {
Edge e = graph[u].get(i);
if (e.cap <= e.f)
continue;
int v = e.to;
int ndist = dist[u] + e.cost;
if (dist[v] > ndist) {
dist[v] = ndist;
if (!inqueue[v]) {
inqueue[v] = true;
q[qt++ % n] = v;
}
}
}
}
}
public static long[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) {
int n = graph.length;
int[] prio = new int[n];
int[] curflow = new int[n];
int[] prevedge = new int[n];
int[] prevnode = new int[n];
int[] pot = new int[n];
bellmanFord(graph, s, pot); // bellmanFord invocation can be skipped if edges costs are non-negative
long flow = 0;
long flowCost = 0;
while (flow < maxf) {
PriorityQueue<Long> q = new PriorityQueue<>();
q.add((long) s);
Arrays.fill(prio, Integer.MAX_VALUE);
prio[s] = 0;
boolean[] finished = new boolean[n];
curflow[s] = Integer.MAX_VALUE;
while (!finished[t] && !q.isEmpty()) {
long cur = q.remove();
int u = (int) (cur & 0xFFFF_FFFFL);
int priou = (int) (cur >>> 32);
if (priou != prio[u])
continue;
finished[u] = true;
for (int i = 0; i < graph[u].size(); i++) {
Edge e = graph[u].get(i);
if (e.f >= e.cap)
continue;
int v = e.to;
int nprio = prio[u] + e.cost + pot[u] - pot[v];
if (prio[v] > nprio) {
prio[v] = nprio;
q.add(((long) nprio << 32) + v);
prevnode[v] = u;
prevedge[v] = i;
curflow[v] = Math.min(curflow[u], e.cap - e.f);
}
}
}
if (prio[t] == Integer.MAX_VALUE)
break;
for (int i = 0; i < n; i++)
if (finished[i])
pot[i] += prio[i] - prio[t];
int df = Math.min(curflow[t], maxf - (int)flow);
flow += df;
for (int v = t; v != s; v = prevnode[v]) {
Edge e = graph[prevnode[v]].get(prevedge[v]);
e.f += df;
graph[v].get(e.rev).f -= df;
flowCost += (long)df * e.cost;
}
}
return new long[]{flow, flowCost};
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
return null;
}
}
public double nextDouble() {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() {
try {
return br.ready();
} catch (Exception e) {
return false;
}
}
}
} | Java | ["8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1"] | 4 seconds | ["32"] | NoteIn the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | Java 8 | standard input | [
"binary search",
"flows",
"graphs"
] | 08b8dbb6e167db69dc965e8ad4835808 | The first line of input contains two space-separated integers n and k (1ββ€βkββ€βnββ€β2200). The second line contains n space-separated integers a1,β...,βan () β the preparation costs. The third line contains n space-separated integers b1,β...,βbn () β the printing costs. | 2,400 | Output the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1β+βai2β+β...β+βaikβ+βbj1β+βbj2β+β...β+βbjk, where 1ββ€βi1β<βi2β<β...β<βikββ€βn, 1ββ€βj1β<βj2β<β...β<βjkββ€βn and i1ββ€βj1, i2ββ€βj2, ..., ikββ€βjk. | standard output | |
PASSED | 08857225a008a2c389ecba2bcdee9855 | train_001.jsonl | 1495958700 | The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).What is the minimum cost of preparation and printing? | 256 megabytes | //package prac;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class Helvetic2017N {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
int[] a = na(n);
int[] b = na(n);
List<Edge> es = new ArrayList<>();
int src = n, sink = n+1;
for(int i = 0;i < n;i++){
es.add(new Edge(src, i, 1, a[i]));
es.add(new Edge(i, sink, 1, b[i]));
if(i+1 < n)es.add(new Edge(i, i+1, 9999, 0));
}
out.println(solveMinCostFlow(compileWD(sink+1, es), src, sink, K));
}
public static class Edge
{
public int from, to;
public int capacity;
public long cost;
public int flow;
public Edge complement;
// public int iniflow;
public Edge(int from, int to, int capacity, long cost) {
this.from = from;
this.to = to;
this.capacity = capacity;
this.cost = cost;
}
@Override
public String toString() {
return "Edge [from=" + from + ", to=" + to + ", capacity="
+ capacity + ", cost=" + cost + "]";
}
}
public static long addNegativeEdge(List<Edge> edges, Edge e, int src, int sink)
{
if(e.cost > 0){
edges.add(e);
return 0;
}else{
e.cost = -e.cost;
edges.add(new Edge(src, e.to, e.capacity, 0));
edges.add(new Edge(e.from, sink, e.capacity, 0));
int d = e.from; e.from = e.to; e.to = d;
edges.add(e);
return (long)e.capacity * -e.cost;
}
}
// TODO test
public static long addMinCapacityConstraintEdge(List<Edge> edges, Edge e, int minCapacity, int src, int sink)
{
e.capacity -= minCapacity;
edges.add(new Edge(src, e.to, minCapacity, 0));
edges.add(new Edge(e.from, sink, minCapacity, 0));
return (long)minCapacity * e.cost;
}
public static Edge[][] compileWD(int n, List<Edge> edges)
{
Edge[][] g = new Edge[n][];
// cloning
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge clone = new Edge(origin.to, origin.from, origin.capacity, -origin.cost);
clone.flow = origin.capacity;
clone.complement = origin;
origin.complement = clone;
edges.add(clone);
}
int[] p = new int[n];
for(Edge e : edges)p[e.from]++;
for(int i = 0;i < n;i++)g[i] = new Edge[p[i]];
for(Edge e : edges)g[e.from][--p[e.from]] = e;
return g;
}
public static class DQ {
public int[] q;
public int n;
protected int pt, ph;
public DQ(int n){ this.n = Integer.highestOneBit(n)<<1; q = new int[this.n]; pt = ph = 0; }
public void addLast(int x){ q[ph] = x; ph = ph+1&n-1; }
public void addFirst(int x){ pt = pt+n-1&n-1; q[pt] = x; }
public int pollFirst(){ int ret = q[pt]; pt = pt+1&n-1; return ret; }
public int pollLast(){ ph = ph+n-1&n-1; int ret = q[ph]; return ret; }
public int getFirst(){ return q[pt]; }
public int getFirst(int k){ return q[pt+k&n-1]; }
public int getLast(){ return q[ph+n-1&n-1]; }
public int getLast(int k){ return q[ph+n-k-1&n-1]; }
public void clear(){ pt = ph = 0; }
public int size(){ return ph-pt+n&n-1; }
public boolean isEmpty(){ return ph==pt; }
}
public static class MinHeapL {
public long[] a;
public int[] map;
public int[] imap;
public int n;
public int pos;
public static long INF = Long.MAX_VALUE;
public MinHeapL(int m)
{
n = Integer.highestOneBit((m+1)<<1);
a = new long[n];
map = new int[n];
imap = new int[n];
Arrays.fill(a, INF);
Arrays.fill(map, -1);
Arrays.fill(imap, -1);
pos = 1;
}
public long add(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}
return ret != -1 ? a[ret] : x;
}
public long update(int ind, long x)
{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}else{
a[ret] = x;
up(ret);
down(ret);
}
return x;
}
public long remove(int ind)
{
if(pos == 1)return INF;
if(imap[ind] == -1)return INF;
pos--;
int rem = imap[ind];
long ret = a[rem];
map[rem] = map[pos];
imap[map[pos]] = rem;
imap[ind] = -1;
a[rem] = a[pos];
a[pos] = INF;
map[pos] = -1;
up(rem);
down(rem);
return ret;
}
public long min() { return a[1]; }
public int argmin() { return map[1]; }
public int size() { return pos-1; }
private void up(int cur)
{
for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){
long d = a[p]; a[p] = a[c]; a[c] = d;
int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e;
e = map[p]; map[p] = map[c]; map[c] = e;
}
}
private void down(int cur)
{
for(int c = cur;2*c < pos;){
int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1;
if(a[b] < a[c]){
long d = a[c]; a[c] = a[b]; a[b] = d;
int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e;
e = map[c]; map[c] = map[b]; map[b] = e;
c = b;
}else{
break;
}
}
}
}
public static long solveMinCostFlow(Edge[][] g, int source, int sink, long all)
{
int n = g.length;
long mincost = 0;
long[] potential = new long[n];
final long[] d = new long[n];
MinHeapL q = new MinHeapL(n);
while(all > 0){
// shortest path src->sink
Edge[] inedge = new Edge[n];
Arrays.fill(d, Integer.MAX_VALUE / 2);
d[source] = 0;
q.add(source, 0);
while(q.size() > 0){
int cur = q.argmin();
q.remove(cur);
for(Edge ne : g[cur]){
if(ne.capacity - ne.flow > 0){
long nd = d[cur] + ne.cost + potential[cur] - potential[ne.to];
if(d[ne.to] > nd){
inedge[ne.to] = ne;
d[ne.to] = nd;
q.update(ne.to, nd);
}
}
}
}
if(inedge[sink] == null)break;
long minflow = all;
long sumcost = 0;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
if(e.capacity - e.flow < minflow)minflow = e.capacity - e.flow;
sumcost += e.cost;
}
mincost += minflow * sumcost;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
e.flow += minflow;
e.complement.flow -= minflow;
}
all -= minflow;
for(int i = 0;i < n;i++){
potential[i] += d[i];
}
}
return mincost;
}
// negative is OK.
public static long solveMinCostFlowWithSPFA(Edge[][] g, int source, int sink, long all)
{
int n = g.length;
long mincost = 0;
final long[] d = new long[n];
DQ q = new DQ(n);
boolean[] inq = new boolean[n];
while(all > 0){
// shortest path src->sink
Edge[] inedge = new Edge[n];
Arrays.fill(d, Long.MAX_VALUE / 2);
d[source] = 0;
q.addLast(source);
while(!q.isEmpty()){
int cur = q.pollFirst();
inq[cur] = false;
for(Edge ne : g[cur]){
if(ne.capacity - ne.flow > 0){
long nd = d[cur] + ne.cost;
if(d[ne.to] > nd){
inedge[ne.to] = ne;
d[ne.to] = nd;
if(!inq[ne.to]){
q.addLast(ne.to);
inq[ne.to] = true;
}
}
}
}
}
if(inedge[sink] == null)break;
long minflow = all;
long sumcost = 0;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
if(e.capacity - e.flow < minflow)minflow = e.capacity - e.flow;
sumcost += e.cost;
}
mincost += minflow * sumcost;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
e.flow += minflow;
e.complement.flow -= minflow;
}
all -= minflow;
}
return mincost;
}
// neagtive is OK, and simple but maybe slower.
public static long solveMinCostFlowWithBellmanFord(Edge[][] g, int source, int sink, long all)
{
int n = g.length;
long mincost = 0;
final long[] d = new long[n];
while(all > 0){
// shortest path src->sink
Edge[] inedge = new Edge[n];
Arrays.fill(d, Long.MAX_VALUE / 2);
d[source] = 0;
int nease = 0;
for(;;nease++){
boolean changed = false;
for(Edge[] row : g){
for(Edge e : row){
if(e.capacity - e.flow > 0){
long nd = d[e.from] + e.cost;
if(nd < d[e.to]){
d[e.to] = nd;
inedge[e.to] = e;
changed = true;
}
}
}
}
if(!changed)break;
if(nease == n-1){
// there are negative circuits.
throw new RuntimeException();
}
}
if(inedge[sink] == null)break;
long minflow = all;
long sumcost = 0;
boolean fromSource = false;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
if(e.capacity - e.flow < minflow)minflow = e.capacity - e.flow;
sumcost += e.cost;
if(e.from == source)fromSource = true;
}
if(!fromSource)break;
mincost += minflow * sumcost;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
e.flow += minflow;
e.complement.flow -= minflow;
}
all -= minflow;
}
return mincost;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Helvetic2017N().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 | ["8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1"] | 4 seconds | ["32"] | NoteIn the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | Java 8 | standard input | [
"binary search",
"flows",
"graphs"
] | 08b8dbb6e167db69dc965e8ad4835808 | The first line of input contains two space-separated integers n and k (1ββ€βkββ€βnββ€β2200). The second line contains n space-separated integers a1,β...,βan () β the preparation costs. The third line contains n space-separated integers b1,β...,βbn () β the printing costs. | 2,400 | Output the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1β+βai2β+β...β+βaikβ+βbj1β+βbj2β+β...β+βbjk, where 1ββ€βi1β<βi2β<β...β<βikββ€βn, 1ββ€βj1β<βj2β<β...β<βjkββ€βn and i1ββ€βj1, i2ββ€βj2, ..., ikββ€βjk. | standard output | |
PASSED | 70890cd41cc7862cb6bbfc9686b74c83 | train_001.jsonl | 1495958700 | The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).What is the minimum cost of preparation and printing? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov ([email protected])
*/
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);
TaskCF solver = new TaskCF();
solver.solve(1, in, out);
out.close();
}
static class TaskCF {
Graph g;
int s;
int t;
int[] a;
int[] b;
int n;
public void build_tree(int v, int tl, int tr) {
if (tl == tr) {
g.addFlowWeightedEdge(3 * n + v, t, b[tl], 1);
} else {
int mid = (tl + tr) / 2;
build_tree(v + v, tl, mid);
build_tree(v + v + 1, mid + 1, tr);
g.addFlowWeightedEdge(3 * n + v, 3 * n + v + v, 0, 10 * n);
g.addFlowWeightedEdge(3 * n + v, 3 * n + v + v + 1, 0, 10 * n);
}
}
public void add_edge(int v, int tl, int tr, int l, int r, int pos) {
if (l > r) {
return;
}
if (l == tl && r == tr) {
g.addFlowWeightedEdge(pos, 3 * n + v, 0, 1);
return;
}
int mid = (tl + tr) / 2;
add_edge(v + v, tl, mid, l, Integer.min(r, mid), pos);
add_edge(v + v + 1, mid + 1, tr, Integer.max(l, mid + 1), r, pos);
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int k = in.readInt();
a = IOUtils.readIntArray(in, n);
b = IOUtils.readIntArray(in, n);
g = new Graph(20 * n + 30);
t = 11 * n + 1;
int t1 = 11 * n + 2;
build_tree(1, 0, n - 1);
for (int i = 0; i < n; ++i) {
g.addFlowWeightedEdge(s, i + 1, a[i], 1);
add_edge(1, 0, n - 1, i, n - 1, i + 1);
}
g.addFlowWeightedEdge(t, t1, 0, k);
out.printLine(MinCostFlow.minCostMaxFlow(g, s, t1, false).first);
}
}
static class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static <U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) &&
!(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
@SuppressWarnings({"unchecked"})
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0) {
return value;
}
return ((Comparable<V>) second).compareTo(o.second);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntQueue extends IntCollection {
}
static class Heap implements IntQueue {
private IntComparator comparator;
private int size = 0;
private int[] elements;
private int[] at;
public Heap(int maxElement) {
this(10, maxElement);
}
public Heap(IntComparator comparator, int maxElement) {
this(10, comparator, maxElement);
}
public Heap(int capacity, int maxElement) {
this(capacity, IntComparator.DEFAULT, maxElement);
}
public Heap(int capacity, IntComparator comparator, int maxElement) {
this.comparator = comparator;
elements = new int[capacity];
at = new int[maxElement];
Arrays.fill(at, -1);
}
public boolean isEmpty() {
return size == 0;
}
public void add(int element) {
ensureCapacity(size + 1);
elements[size] = element;
at[element] = size;
shiftUp(size++);
}
public void shiftUp(int index) {
// if (index < 0 || index >= size)
// throw new IllegalArgumentException();
int value = elements[index];
while (index != 0) {
int parent = (index - 1) >>> 1;
int parentValue = elements[parent];
if (comparator.compare(parentValue, value) <= 0) {
elements[index] = value;
at[value] = index;
return;
}
elements[index] = parentValue;
at[parentValue] = index;
index = parent;
}
elements[0] = value;
at[value] = 0;
}
public void shiftDown(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException();
}
while (true) {
int child = (index << 1) + 1;
if (child >= size) {
return;
}
if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) {
child++;
}
if (comparator.compare(elements[index], elements[child]) <= 0) {
return;
}
swap(index, child);
index = child;
}
}
public int getIndex(int element) {
return at[element];
}
private void swap(int first, int second) {
int temp = elements[first];
elements[first] = elements[second];
elements[second] = temp;
at[elements[first]] = first;
at[elements[second]] = second;
}
private void ensureCapacity(int size) {
if (elements.length < size) {
int[] oldElements = elements;
elements = new int[Math.max(2 * elements.length, size)];
System.arraycopy(oldElements, 0, elements, 0, this.size);
}
}
public int poll() {
if (isEmpty()) {
throw new IndexOutOfBoundsException();
}
int result = elements[0];
at[result] = -1;
if (size == 1) {
size = 0;
return result;
}
elements[0] = elements[--size];
at[elements[0]] = 0;
shiftDown(0);
return result;
}
public IntIterator intIterator() {
return new IntIterator() {
private int at;
public int value() throws NoSuchElementException {
return elements[at];
}
public boolean advance() throws NoSuchElementException {
return ++at < size;
}
public boolean isValid() {
return at < size;
}
public void remove() throws NoSuchElementException {
throw new UnsupportedOperationException();
}
};
}
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
public long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1) {
nextOutbound[edgeCount] = firstOutbound[fromID];
} else {
nextOutbound[edgeCount] = -1;
}
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1) {
nextInbound[edgeCount] = firstInbound[toID];
} else {
nextInbound[edgeCount] = -1;
}
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null) {
this.capacity = new long[from.length];
}
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null) {
this.weight = new long[from.length];
}
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null) {
edges[edgeCount] = createEdge(edgeCount);
}
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int vertexCount() {
return vertexCount;
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id)) {
id = nextOutbound[id];
}
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id)) {
id = nextOutbound[id];
}
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null) {
return 0;
}
return weight[id];
}
public final long capacity(int id) {
if (capacity == null) {
return 0;
}
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null) {
return 0;
}
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0) {
return;
}
if (flow > 0) {
if (capacity(id) < flow) {
throw new IllegalArgumentException("Not enough capacity");
}
} else {
if (flow(id) < -flow) {
throw new IllegalArgumentException("Not enough capacity");
}
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null) {
edges = resize(edges, newSize);
}
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null) {
nextInbound = resize(nextInbound, newSize);
}
if (weight != null) {
weight = resize(weight, newSize);
}
if (capacity != null) {
capacity = resize(capacity, newSize);
}
if (reverseEdge != null) {
reverseEdge = resize(reverseEdge, newSize);
}
flags = resize(flags, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
}
}
static class IntegerUtils {
public static int longCompare(long a, long b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
}
static interface IntCollection extends IntStream {
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = in.readInt();
}
return array;
}
}
static class MinCostFlow {
private final Graph graph;
private final int source;
private final int destination;
private final long[] phi;
private final long[] dijkstraResult;
private final int[] lastEdge;
private final Heap heap;
private final int vertexCount;
private final int[] visited;
private int visitIndex;
public MinCostFlow(Graph graph, int source, int destination, boolean hasNegativeEdges) {
this.graph = graph;
this.source = source;
this.destination = destination;
vertexCount = graph.vertexCount();
phi = new long[vertexCount];
if (hasNegativeEdges) {
fordBellman();
}
dijkstraResult = new long[vertexCount];
lastEdge = new int[vertexCount];
if (graph.isSparse()) {
heap = new Heap(vertexCount, new IntComparator() {
public int compare(int first, int second) {
return IntegerUtils.longCompare(dijkstraResult[first], dijkstraResult[second]);
}
}, vertexCount);
visited = null;
} else {
heap = null;
visited = new int[vertexCount];
}
}
private void fordBellman() {
Arrays.fill(phi, Long.MAX_VALUE);
phi[source] = 0;
boolean[] inQueue = new boolean[vertexCount];
int[] queue = new int[vertexCount + 1];
queue[0] = source;
inQueue[source] = true;
int stepCount = 0;
int head = 0;
int end = 1;
int maxSteps = 2 * vertexCount * vertexCount;
while (head != end) {
int vertex = queue[head++];
if (head == queue.length) {
head = 0;
}
inQueue[vertex] = false;
int edgeID = graph.firstOutbound(vertex);
while (edgeID != -1) {
long total = phi[vertex] + graph.weight(edgeID);
int destination = graph.destination(edgeID);
if (graph.capacity(edgeID) != 0 && phi[destination] > total) {
phi[destination] = total;
if (!inQueue[destination]) {
queue[end++] = destination;
inQueue[destination] = true;
if (end == queue.length) {
end = 0;
}
}
}
edgeID = graph.nextOutbound(edgeID);
}
if (++stepCount > maxSteps) {
throw new IllegalArgumentException("Graph contains negative cycle");
}
}
}
public static Pair<Long, Long> minCostMaxFlow(Graph graph, int source, int destination,
boolean hasNegativeEdges) {
return new MinCostFlow(graph, source, destination, hasNegativeEdges).minCostMaxFlow();
}
public Pair<Long, Long> minCostMaxFlow() {
return minCostMaxFlow(Long.MAX_VALUE);
}
public Pair<Long, Long> minCostMaxFlow(long maxFlow) {
long cost = 0;
long flow = 0;
while (maxFlow != 0) {
if (graph.isSparse()) {
dijkstraAlgorithm();
} else {
dijkstraAlgorithmFull();
}
if (lastEdge[destination] == -1) {
return Pair.makePair(cost, flow);
}
for (int i = 0; i < dijkstraResult.length; i++) {
if (dijkstraResult[i] != Long.MAX_VALUE) {
phi[i] += dijkstraResult[i];
}
}
int vertex = destination;
long currentFlow = maxFlow;
long currentCost = 0;
while (vertex != source) {
int edgeID = lastEdge[vertex];
currentFlow = Math.min(currentFlow, graph.capacity(edgeID));
currentCost += graph.weight(edgeID);
vertex = graph.source(edgeID);
}
maxFlow -= currentFlow;
cost += currentCost * currentFlow;
flow += currentFlow;
vertex = destination;
while (vertex != source) {
int edgeID = lastEdge[vertex];
graph.pushFlow(edgeID, currentFlow);
vertex = graph.source(edgeID);
}
}
return Pair.makePair(cost, flow);
}
private void dijkstraAlgorithm() {
Arrays.fill(dijkstraResult, Long.MAX_VALUE);
Arrays.fill(lastEdge, -1);
dijkstraResult[source] = 0;
heap.add(source);
while (!heap.isEmpty()) {
int current = heap.poll();
int edgeID = graph.firstOutbound(current);
while (edgeID != -1) {
if (graph.capacity(edgeID) != 0) {
int next = graph.destination(edgeID);
long total = graph.weight(edgeID) - phi[next] + phi[current] + dijkstraResult[current];
if (dijkstraResult[next] > total) {
dijkstraResult[next] = total;
if (heap.getIndex(next) == -1) {
heap.add(next);
} else {
heap.shiftUp(heap.getIndex(next));
}
lastEdge[next] = edgeID;
}
}
edgeID = graph.nextOutbound(edgeID);
}
}
}
private void dijkstraAlgorithmFull() {
visitIndex++;
Arrays.fill(dijkstraResult, Long.MAX_VALUE);
lastEdge[destination] = -1;
dijkstraResult[source] = 0;
for (int i = 0; i < vertexCount; i++) {
int index = -1;
long length = Long.MAX_VALUE;
for (int j = 0; j < vertexCount; j++) {
if (visited[j] != visitIndex && dijkstraResult[j] < length) {
length = dijkstraResult[j];
index = j;
}
}
if (index == -1) {
return;
}
visited[index] = visitIndex;
int edgeID = graph.firstOutbound(index);
while (edgeID != -1) {
if (graph.capacity(edgeID) != 0) {
int next = graph.destination(edgeID);
if (visited[next] != visitIndex) {
long total = graph.weight(edgeID) - phi[next] + phi[index] + length;
if (dijkstraResult[next] > total) {
dijkstraResult[next] = total;
lastEdge[next] = edgeID;
}
}
}
edgeID = graph.nextOutbound(edgeID);
}
}
}
}
static interface Edge {
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static interface IntComparator {
public static final IntComparator DEFAULT = (first, second) -> {
if (first < second) {
return -1;
}
if (first > second) {
return 1;
}
return 0;
};
public int compare(int first, int second);
}
}
| Java | ["8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1"] | 4 seconds | ["32"] | NoteIn the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | Java 8 | standard input | [
"binary search",
"flows",
"graphs"
] | 08b8dbb6e167db69dc965e8ad4835808 | The first line of input contains two space-separated integers n and k (1ββ€βkββ€βnββ€β2200). The second line contains n space-separated integers a1,β...,βan () β the preparation costs. The third line contains n space-separated integers b1,β...,βbn () β the printing costs. | 2,400 | Output the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1β+βai2β+β...β+βaikβ+βbj1β+βbj2β+β...β+βbjk, where 1ββ€βi1β<βi2β<β...β<βikββ€βn, 1ββ€βj1β<βj2β<β...β<βjkββ€βn and i1ββ€βj1, i2ββ€βj2, ..., ikββ€βjk. | standard output | |
PASSED | 07051281eea06341195fa8c81b4279bc | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static class Pair implements Comparable<Pair> {
int b,e;
int ind;
@Override
public int compareTo(Pair o) {
return b - o.b;
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
//Scanner in = new Scanner (new File("input.txt"));
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
Pair[] p = new Pair[n];
for (int i=0; i<n; i++){
Pair p1 = new Main.Pair();
p1.b = in.nextInt();
p1.e = in.nextInt();
p1.ind = i+1;
p[i] = p1;
}
ArrayList<Integer> res = new ArrayList<Integer>();
Arrays.sort(p);
for (int i=0; i<n; i++) {
int prv = -1;
boolean can = true;
for (int u=0; u<n; u++) {
if (u == i) {
continue;
}
if (prv == -1) {
prv = u;
continue;
}
if (p[u].b < p[prv].e) {
can = false;
break;
}
prv = u;
}
if (can)
res.add(p[i].ind);
}
out.println(res.size());
Collections.sort(res);
for (int i=0; i<res.size(); i++) {
out.print(res.get(i) + " ");
}
out.close();
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | e5ae48dab469ee456be17e9b0c6377cc | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int n = r.nextInt();
int[][] a = new int[n][2];
for(int i = 0; i < n; i++)
for(int j = 0; j < 2; j++)
a[i][j] = r.nextInt();
int[] cnt = new int[n];
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; i++)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){
if(i == j)continue;
if(intersect(a[i], a[j])){
adj[i].add(j);
adj[j].add(i);
cnt[i]++;
cnt[j]++;
}
}
}
ArrayList<Integer> res = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
for(int j:adj[i])
cnt[j]--;
boolean can = true;
for(int k = 0; k < n && can; k++){
if(i == k)continue;
if(cnt[k] > 0)can = false;
}
if(can)res.add(i+1);
for(int j:adj[i])
cnt[j]++;
}
System.out.println(res.size());
for(int j : res)
System.out.println(j);
}
static boolean intersect(int[] a, int[] b){
if(a[1] <= b[0] || a[0] >= b[1])return false;
else return true;
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 3f76be6e5b85f973ba5228afd959d3c5 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class C_Schedule {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Event> events = new ArrayList<Event>();
for (int i = 0; i < n; i++) {
events.add(new Event(i, sc.nextInt(), true));
events.add(new Event(i, sc.nextInt(), false));
}
Collections.sort(events, new Comparator<Event>() {
public int compare(Event o1, Event o2) {
if(o1.time == o2.time){
return o1.start ? 1 : -1;
}else{
return o1.time - o2.time;
}
}
});
boolean[] ps = new boolean[n];
List<Integer> indice = new ArrayList<Integer>();
int cnt = 0;
for(Event e : events){
if(e.start){
if(cnt >= 2){
System.out.println(0);
return;
}else{
if(cnt == 1){
int i = 0;
for (; i < n; i++) if(ps[i]) break;
if(indice.size() == 2){
for (int j = 0; j < 2; j++) {
if(indice.get(j) != i){
indice.remove(j);
break;
}
}
}else if(indice.size() == 1 && indice.get(0) != i){
System.out.println(0);
return;
}else if(indice.size() == 0){
indice.add(i);
indice.add(e.index);
}
}
ps[e.index] = true;
cnt++;
}
}else{
cnt--;
ps[e.index] = false;
}
}
Collections.sort(indice);
if(indice.size() == 0){
System.out.println(n);
for (int i = 0; i < n; i++) {
System.out.print(i+1);
System.out.print(" ");
}
}else{
System.out.println(indice.size());
for (Integer i : indice) {
System.out.print(i+1);
System.out.print(" ");
}
}
}
private static class Event{
int index;
int time;
boolean start;
public Event(int index, int time, boolean start) {
this.index = index;
this.time = time;
this.start = start;
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 02eb0584bea2f257bf4bf6a8e924c268 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class C_Schedule {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] start = new int[n];
int[] end = new int[n];
Node[] nodes = new Node[n];
for (int i = 0; i < n; i++) {
start[i] = sc.nextInt();
end[i] = sc.nextInt();
nodes[i] = new Node(i);
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if(!(end[j] <= start[i] || start[j] >= end[i])){
nodes[i].links.add(nodes[j]);
nodes[j].links.add(nodes[i]);
}
}
}
List<List<Node>> groups = new ArrayList<List<Node>>();
boolean[] checked = new boolean[n];
for (int i = 0; i < n; i++) {
if(checked[nodes[i].index]) continue;
checked[nodes[i].index] = true;
List<Node> group = new ArrayList<Node>();
Stack<Node> st = new Stack<Node>();
st.push(nodes[i]);
while(! st.isEmpty()){
Node cur = st.pop();
group.add(cur);
for(Node l : cur.links){
if(checked[l.index]) continue;
checked[l.index] = true;
st.push(l);
}
}
groups.add(group);
}
Iterator<List<Node>> iter = groups.iterator();
while(iter.hasNext()){
if(iter.next().size() == 1) iter.remove();
}
if(groups.size() > 1){
System.out.println(0);
return;
}else if(groups.size() == 0){
System.out.println(n);
for (int i = 0; i < n; i++) {
System.out.print(i+1);
System.out.print(" ");
}
}else{
if(groups.get(0).size() == 2){
List<Node> g = groups.get(0);
System.out.println(2);
System.out.println(String.format("%s %s", Math.min(g.get(0).index, g.get(1).index)+1, Math.max(g.get(0).index, g.get(1).index)+1));
}else{
int mulcnt = 0;
Node maxNode = null;
for(Node node : groups.get(0)){
if(node.links.size() > 1){
mulcnt++;
maxNode = node;
}
}
if(mulcnt >1){
System.out.println(0);
return;
}
System.out.println(1);
System.out.println(maxNode.index+1);
}
}
}
static class Node{
int index;
List<Node> links;
public Node(int index){
this.index = index;
this.links = new ArrayList<Node>();
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 6f77b7d5d3e221d9f96516e3320eeffb | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Schedule {
/**
* @param args
*/
static class Section {
int left;
int right;
int index;
static boolean isIntersect(Section a, Section b) {
if (a.right > b.left) {
return true;
}
else {
return false;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
while(cin.hasNext()) {
int n = cin.nextInt();
Section[] ln = new Section[n];
for (int i = 0; i < n; i++) {
ln[i] = new Section();
ln[i].left = cin.nextInt();
ln[i].right = cin.nextInt();
ln[i].index = i + 1;
}
Arrays.sort(ln, new Comparator<Section>() {
@Override
public int compare(Section o1, Section o2) {
// TODO Auto-generated method stub
if (o1.left == o2.left) {
return o1.right - o2.right;
}
else {
return o1.left - o2.left;
}
}
});
List<Integer> out = new ArrayList<Integer>();
for (int i = 0; i < ln.length; i++) {
boolean intersect = false;
Section pre = ln[0];
for (int j = 1; j < ln.length; j++) {
if (i != j) {
if (Section.isIntersect(pre, ln[j])) {
intersect = true;
break;
}
pre = ln[j];
}
}
if (intersect == false) {
out.add(ln[i].index);
}
}
Collections.sort(out);
System.out.println(out.size());
final Integer[] temp = out.toArray(new Integer[0]);
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1) {
System.out.println(temp[i]);
}
else {
System.out.print(temp[i] + " ");
}
}
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 0cea664be5fe50319e85926deabd1de7 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | //package timus;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.Writer;
import java.math.BigInteger;
import java.sql.Date;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
public class Abra {
public static void main(String[] args) throws IOException {
new Abra().run();
}
StreamTokenizer in;
PrintWriter out;
boolean oj;
BufferedReader br;
void init() throws IOException {
oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
// Reader reader = new InputStreamReader(System.in);
// Writer writer = new OutputStreamWriter(System.out);
br = new BufferedReader(reader);
in = new StreamTokenizer(br);
out = new PrintWriter(writer);
}
long selectionTime = 0;
void startSelection() {
selectionTime -= System.currentTimeMillis();
}
void stopSelection() {
selectionTime += System.currentTimeMillis();
}
void run() throws IOException {
long beginTime = System.currentTimeMillis();
init();
solve();
long endTime = System.currentTimeMillis();
if (!oj) {
System.out.println("Memory used = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
System.out.println("Running time = " + (endTime - beginTime));
System.out.println("Time of the selection = " + selectionTime);
}
out.flush();
}
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
long fact(long x) {
long a = 1;
for (long i = 2; i <= x; i++) {
a *= i;
}
return a;
}
long digitSum(String x) {
long a = 0;
for (int i = 0; i < x.length(); i++) {
a += x.charAt(i) - '0';
}
return a;
}
long digitSum(long x) {
long a = 0;
while (x > 0) {
a += x % 10;
x /= 10;
}
return a;
}
long digitMul(long x) {
long a = 1;
while (x > 0) {
a *= x % 10;
x /= 10;
}
return a;
}
int digitCubesSum(int x) {
int a = 0;
while (x > 0) {
a += (x % 10) * (x % 10) * (x % 10);
x /= 10;
}
return a;
}
double pif(double ax, double ay, double bx, double by) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
long gcd(long a, long b) {
if (a < b) {
long c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
long c = b;
b = a;
a = c;
}
}
return b;
}
int gcd(int a, int b) {
if (a < b) {
int c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
int c = b;
b = a;
a = c;
}
}
return b;
}
long lcm(long a, long b) throws IOException {
return a * b / gcd(a, b);
}
int lcm(int a, int b) throws IOException {
return a * b / gcd(a, b);
}
int countOccurences(String x, String y) {
int a = 0, i = 0;
while (true) {
i = y.indexOf(x);
if (i == -1) break;
a++;
y = y.substring(i + 1);
}
return a;
}
int[] findPrimes(int x) {
boolean[] forErato = new boolean[x - 1];
List<Integer> t = new Vector<Integer>();
int l = 0, j = 0;
for (int i = 2; i < x; i++) {
if (forErato[i - 2]) continue;
t.add(i);
l++;
j = i * 2;
while (j < x) {
forErato[j - 2] = true;
j += i;
}
}
int[] primes = new int[l];
Iterator<Integer> iterator = t.iterator();
for (int i = 0; iterator.hasNext(); i++) {
primes[i] = iterator.next().intValue();
}
return primes;
}
int rev(int x) {
int a = 0;
while (x > 0) {
a = a * 10 + x % 10;
x /= 10;
}
return a;
}
class myDate {
int d, m, y;
int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public myDate(int da, int ma, int ya) {
d = da;
m = ma;
y = ya;
if (ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) {
d = 1;
m = 1;
y = 9999999;
}
}
void incYear(int x) {
for (int i = 0; i < x; i++) {
y++;
if (m == 2 && d == 29) {
m = 3;
d = 1;
return;
}
if (m == 3 && d == 1) {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
m = 2;
d = 29;
}
return;
}
}
}
boolean less(myDate x) {
if (y < x.y) return true;
if (y > x.y) return false;
if (m < x.m) return true;
if (m > x.m) return false;
if (d < x.d) return true;
if (d > x.d) return false;
return true;
}
void inc() {
if ((d == 31) && (m == 12)) {
y++;
d = 1;
m = 1;
} else {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
ml[1] = 29;
}
if (d == ml[m - 1]) {
m++;
d = 1;
} else
d++;
}
}
}
int partition(int n, int l, int m) {// n - sum, l - length, m - every part
// <= m
if (n < l) return 0;
if (n < l + 2) return 1;
if (l == 1) return 1;
int c = 0;
for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) {
c += partition(n - i, l - 1, i);
}
return c;
}
int rifmQuality(String a, String b) {
if (a.length() > b.length()) {
String c = a;
a = b;
b = c;
}
int c = 0, d = b.length() - a.length();
for (int i = a.length() - 1; i >= 0; i--) {
if (a.charAt(i) == b.charAt(i + d)) c++;
else
break;
}
return c;
}
String numSym = "0123456789ABCDEF";
String ZFromXToYNotation(int x, int y, String z) {
if (z.equals("0")) return "0";
String a = "";
long q = 0, t = 1;
for (int i = z.length() - 1; i >= 0; i--) {
q += (z.charAt(i) - 48) * t;
t *= x;
}
while (q > 0) {
a = numSym.charAt((int) (q % y)) + a;
q /= y;
}
return a;
}
double angleFromXY(int x, int y) {
if ((x == 0) && (y > 0)) return Math.PI / 2;
if ((x == 0) && (y < 0)) return -Math.PI / 2;
if ((y == 0) && (x > 0)) return 0;
if ((y == 0) && (x < 0)) return Math.PI;
if (x > 0) return Math.atan((double) y / x);
else {
if (y > 0) return Math.atan((double) y / x) + Math.PI;
else
return Math.atan((double) y / x) - Math.PI;
}
}
static boolean isNumber(String x) {
try {
Integer.parseInt(x);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
static boolean stringContainsOf(String x, String c) {
for (int i = 0; i < x.length(); i++) {
if (c.indexOf(x.charAt(i)) == -1) return false;
}
return true;
}
long pow(long a, long n) { // b > 0
if (n == 0) return 1;
long k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
int pow(int a, int n) { // b > 0
if (n == 0) return 1;
int k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double pow(double a, int n) { // b > 0
if (n == 0) return 1;
double k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double log2(double x) {
return Math.log(x) / Math.log(2);
}
int lpd(int[] primes, int x) {// least prime divisor
int i;
for (i = 0; primes[i] <= x / 2; i++) {
if (x % primes[i] == 0) {
return primes[i];
}
}
;
return x;
}
int np(int[] primes, int x) {// number of prime number
for (int i = 0; true; i++) {
if (primes[i] == x) return i;
}
}
int[] dijkstra(int[][] map, int n, int s) {
int[] p = new int[n];
boolean[] b = new boolean[n];
Arrays.fill(p, Integer.MAX_VALUE);
p[s] = 0;
b[s] = true;
for (int i = 0; i < n; i++) {
if (i != s) p[i] = map[s][i];
}
while (true) {
int m = Integer.MAX_VALUE, mi = -1;
for (int i = 0; i < n; i++) {
if (!b[i] && (p[i] < m)) {
mi = i;
m = p[i];
}
}
if (mi == -1) break;
b[mi] = true;
for (int i = 0; i < n; i++)
if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i];
}
return p;
}
boolean isLatinChar(char x) {
if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true;
else
return false;
}
boolean isBigLatinChar(char x) {
if (x >= 'A' && x <= 'Z') return true;
else
return false;
}
boolean isSmallLatinChar(char x) {
if (x >= 'a' && x <= 'z') return true;
else
return false;
}
boolean isDigitChar(char x) {
if (x >= '0' && x <= '9') return true;
else
return false;
}
class NotANumberException extends Exception {
private static final long serialVersionUID = 1L;
String mistake;
NotANumberException() {
mistake = "Unknown.";
}
NotANumberException(String message) {
mistake = message;
}
}
class Real {
String num = "0";
long exp = 0;
boolean pos = true;
long length() {
return num.length();
}
void check(String x) throws NotANumberException {
if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character.");
long j = 0;
for (long i = 0; i < x.length(); i++) {
if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) {
if (j == 0) j = 1;
else
if (j == 5) j = 6;
else
throw new NotANumberException("Unexpected sign.");
} else
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) j = 2;
else
if (j == 1) j = 2;
else
if (j == 2)
;
else
if (j == 3) j = 4;
else
if (j == 4)
;
else
if (j == 5) j = 6;
else
if (j == 6)
;
else
throw new NotANumberException("Unexpected digit.");
} else
if (x.charAt((int) i) == '.') {
if (j == 0) j = 3;
else
if (j == 1) j = 3;
else
if (j == 2) j = 3;
else
throw new NotANumberException("Unexpected dot.");
} else
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
if (j == 2) j = 5;
else
if (j == 4) j = 5;
else
throw new NotANumberException("Unexpected exponent.");
} else
throw new NotANumberException("O_o.");
}
if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end.");
}
public Real(String x) throws NotANumberException {
check(x);
if (x.charAt(0) == '-') pos = false;
long j = 0;
String e = "";
boolean epos = true;
for (long i = 0; i < x.length(); i++) {
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) num += x.charAt((int) i);
if (j == 1) {
num += x.charAt((int) i);
exp--;
}
if (j == 2) e += x.charAt((int) i);
}
if (x.charAt((int) i) == '.') {
if (j == 0) j = 1;
}
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
j = 2;
if (x.charAt((int) (i + 1)) == '-') epos = false;
}
}
while ((num.length() > 1) && (num.charAt(0) == '0'))
num = num.substring(1);
while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) {
num = num.substring(0, num.length() - 1);
exp++;
}
if (num.equals("0")) {
exp = 0;
pos = true;
return;
}
while ((e.length() > 1) && (e.charAt(0) == '0'))
e = e.substring(1);
try {
if (e != "") if (epos) exp += Long.parseLong(e);
else
exp -= Long.parseLong(e);
} catch (NumberFormatException exc) {
if (!epos) {
num = "0";
exp = 0;
pos = true;
} else {
throw new NotANumberException("Too long exponent");
}
}
}
public Real() {
}
String toString(long mantissa) {
String a = "", b = "";
if (exp >= 0) {
a = num;
if (!pos) a = '-' + a;
for (long i = 0; i < exp; i++)
a += '0';
for (long i = 0; i < mantissa; i++)
b += '0';
if (mantissa == 0) return a;
else
return a + "." + b;
} else {
if (exp + length() <= 0) {
a = "0";
if (mantissa == 0) {
return a;
}
if (mantissa < -(exp + length() - 1)) {
for (long i = 0; i < mantissa; i++)
b += '0';
return a + "." + b;
} else {
if (!pos) a = '-' + a;
for (long i = 0; i < mantissa; i++)
if (i < -(exp + length())) b += '0';
else
if (i + exp >= 0) b += '0';
else
b += num.charAt((int) (i + exp + length()));
return a + "." + b;
}
} else {
if (!pos) a = "-";
for (long i = 0; i < exp + length(); i++)
a += num.charAt((int) i);
if (mantissa == 0) return a;
for (long i = exp + length(); i < exp + length() + mantissa; i++)
if (i < length()) b += num.charAt((int) i);
else
b += '0';
return a + "." + b;
}
}
}
}
boolean containsRepeats(int... num) {
Set<Integer> s = new TreeSet<Integer>();
for (int d : num)
if (!s.contains(d)) s.add(d);
else
return true;
return false;
}
int[] rotateDice(int[] a, int n) {
int[] c = new int[6];
if (n == 0) {
c[0] = a[1];
c[1] = a[5];
c[2] = a[2];
c[3] = a[0];
c[4] = a[4];
c[5] = a[3];
}
if (n == 1) {
c[0] = a[2];
c[1] = a[1];
c[2] = a[5];
c[3] = a[3];
c[4] = a[0];
c[5] = a[4];
}
if (n == 2) {
c[0] = a[3];
c[1] = a[0];
c[2] = a[2];
c[3] = a[5];
c[4] = a[4];
c[5] = a[1];
}
if (n == 3) {
c[0] = a[4];
c[1] = a[1];
c[2] = a[0];
c[3] = a[3];
c[4] = a[5];
c[5] = a[2];
}
if (n == 4) {
c[0] = a[0];
c[1] = a[2];
c[2] = a[3];
c[3] = a[4];
c[4] = a[1];
c[5] = a[5];
}
if (n == 5) {
c[0] = a[0];
c[1] = a[4];
c[2] = a[1];
c[3] = a[2];
c[4] = a[3];
c[5] = a[5];
}
return c;
}
int min(int... a) {
int c = Integer.MAX_VALUE;
for (int d : a)
if (d < c) c = d;
return c;
}
int max(int... a) {
int c = Integer.MIN_VALUE;
for (int d : a)
if (d > c) c = d;
return c;
}
int[] normalizeDice(int[] a) {
int[] c = a.clone();
if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0);
else
if (c[2] == 0) c = rotateDice(c, 1);
else
if (c[3] == 0) c = rotateDice(c, 2);
else
if (c[4] == 0) c = rotateDice(c, 3);
else
if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0);
while (c[1] != min(c[1], c[2], c[3], c[4]))
c = rotateDice(c, 4);
return c;
}
boolean sameDice(int[] a, int[] b) {
for (int i = 0; i < 6; i++)
if (a[i] != b[i]) return false;
return true;
}
final double goldenRatio = (1 + Math.sqrt(5)) / 2;
final double aGoldenRatio = (1 - Math.sqrt(5)) / 2;
long Fib(int n) {
if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
else
return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5));
}
class japaneeseComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int ai = 0, bi = 0;
boolean m = false, ns = false;
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true;
else
return -1;
}
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true;
else
return 1;
}
a += "!";
b += "!";
int na = 0, nb = 0;
while (true) {
if (a.charAt(ai) == '!') {
if (b.charAt(bi) == '!') break;
return -1;
}
if (b.charAt(bi) == '!') {
return 1;
}
if (m) {
int ab = -1, bb = -1;
while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (ab == -1) ab = ai;
ai++;
}
while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (bb == -1) bb = bi;
bi++;
}
m = !m;
if (ab == -1) {
if (bb == -1) continue;
else
return 1;
}
if (bb == -1) return -1;
while (a.charAt(ab) == '0' && ab + 1 != ai) {
ab++;
if (!ns) na++;
}
while (b.charAt(bb) == '0' && bb + 1 != bi) {
bb++;
if (!ns) nb++;
}
if (na != nb) ns = true;
if (ai - ab < bi - bb) return -1;
if (ai - ab > bi - bb) return 1;
for (int i = 0; i < ai - ab; i++) {
if (a.charAt(ab + i) < b.charAt(bb + i)) return -1;
if (a.charAt(ab + i) > b.charAt(bb + i)) return 1;
}
} else {
m = !m;
while (true) {
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') {
if (a.charAt(ai) < b.charAt(bi)) return -1;
if (a.charAt(ai) > b.charAt(bi)) return 1;
ai++;
bi++;
} else
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1;
else
if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1;
else
break;
}
}
}
if (na < nb) return 1;
if (na > nb) return -1;
return 0;
}
}
void mpr(int x) {
out.print(' ');
if (x < 100) out.print(' ');
if (x < 10) out.print(' ');
out.print(x);
}
int mtry(String s, String alph) {
String t = "";
Random r = new Random();
int c = 0, l = alph.length();
for (int i = 0; i < s.length(); i++) {
t += alph.charAt(r.nextInt(l));
c++;
}
while (!t.equals(s)) {
t = t.substring(1);
t += alph.charAt(r.nextInt(l));
c++;
}
return c;
}
Hashtable<String, Vector> tab;
void mtest(String s, String alph, int d) {
int n = d, r = 0;
for (int i = 0; i < n; i++) {
r += mtry(s, alph);
}
int re = (int) Math.round((0.0 + r) / n);
out.println("\"" + s + "\" = " + re + ", Average = " + ((0.0 + r) / n));
/* String res = Integer.toString(re);
if (!tab.contains(res)) {
tab.put(res, new Vector<String>());
}
tab.get(res).add(s);*/
}
void solve() throws IOException {
/*
* String[] st = new String[52000]; in.resetSyntax(); in.wordChars(' ' +
* 1, 255); in.whitespaceChars(0, ' '); int n = 0; while (true) { String
* t = nextString(); if (in.ttype == StreamTokenizer.TT_EOF) break;
* st[n] = t; n++; } st = Arrays.copyOf(st, n); Arrays.sort(st, new
* japaneeseComparator()); for (int i = 0; i < n; i++) {
* out.println(st[i]); }
*/
int[] a = new int[1000000];
Vector r = new Vector();
int n = nextInt();
int no = 0;
int[][] in = new int[n][2];
for (int i = 0; i < n; i++) {
int x = nextInt(), y = nextInt();
for (int j = x; j < y; j++) {
if (a[j] == 0) {
a[j] = 1;
continue;
}
if (a[j] == 1) {
a[j] = 2;
no++;
continue;
}
if (a[j] == 2) {
out.print(0);
return;
}
}
in[i][0] = x;
in[i][1] = y;
}
for (int i = 0; i < n; i++) {
int t = 0;
for (int j = in[i][0]; j < in[i][1]; j++) {
if (a[j] == 2) t++;
}
if (t == no) r.add(i);
}
out.println(r.size());
for (int i = 0; i < r.size(); i++) {
out.print(((Integer)r.get(i) + 1) + " ");
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 4283e2e0c459db47cd27f3f2ced41a87 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes |
import java.util.*;
public class C
{
public static void main(String[] args)
{
new C(new Scanner(System.in));
}
vect[] vs;
int N;
boolean test(vect p, vect q)
{
if (p.y <= q.x) return false;
if (q.y <= p.x) return false;
return true;
}
ArrayList<Integer> go()
{
ArrayList<Integer> res = new ArrayList<Integer>();
ArrayList<Integer> mcnt = new ArrayList<Integer>();
int size = -1;
for (int i=0; i<N; i++)
{
int cnt = 0;
for (int j=0; j<N; j++)
{
if (i == j) continue;
if (test(vs[i], vs[j]))
cnt++;
}
if (cnt > 0)
res.add(i);
if (cnt > 1)
{
mcnt.add(i);
size = cnt;
}
}
if (mcnt.size() > 1)
return new ArrayList<Integer>();
if (res.size() == 0)
{
for (int i=0; i<N; i++)
res.add(i);
return res;
}
if (mcnt.size() == 1)
{
if (res.size() == (size+1))
return mcnt;
return new ArrayList<Integer>();
}
if (res.size() == 2)
return res;
return new ArrayList<Integer>();
}
public C(Scanner in)
{
N = in.nextInt();
vs = new vect[N];
for (int i=0; i<N; i++)
vs[i] = new vect(in.nextInt(), in.nextInt());
ArrayList<Integer> res = go();
System.out.printf("%d%n", res.size());
if (res.size() == 0) return;
StringBuilder sb = new StringBuilder();
for (int v : res)
{
sb.append(v+1);
sb.append(' ');
}
System.out.println(sb.toString().trim());
}
}
class vect
{
int x, y;
public vect(int i, int j)
{
x=i; y=j;
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 7ded590cd882f13d0f5e5520d0502f33 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws Exception {
in = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-9"));
out = new PrintWriter(System.out);
st = new StreamTokenizer(in);
solve();
in.close();
out.close();
}
private static void solve() throws Exception {
int N = nextInt();
int[][] otr = new int[N][2];
for (int i = 0; i < N; i++) {
for (int j = 0; j < 2; j++) {
otr[i][j] = nextInt();
}
}
boolean[][] gr = new boolean[N][N];
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
gr[i][j] = gr[j][i] = peres(otr[i], otr[j]) || peres(otr[j], otr[i]);
}
}
int allCount = 0;
int[] count = new int[N];
for (int i = 0; i < N; i++) {
int cnt = 0;
for (int j = 0; j < N; j++) {
if (gr[i][j])
++cnt;
}
count[i] = cnt;
allCount += cnt;
}
ArrayList<Integer> ans = new ArrayList<Integer>();
for (int k = 0; k < N; k++) {
if (allCount == count[k] * 2)
ans.add(k);
}
out.println(ans.size());
for (int v : ans) {
out.print(v + 1);
out.print(' ');
}
}
private static boolean peres(int[] a, int[] b) {
if (a[0] == b[0] && a[1] == b[1])
return true;
return a[0] < b[0] && b[0] < a[1] || a[0] < b[1] && b[1] < a[1];
}
static StreamTokenizer st;
static BufferedReader in;
static PrintWriter out;
static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
static double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
static String nextString() throws IOException {
st.nextToken();
return st.sval;
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 209ab8c7150fd22a3d75ab8fe7ad8517 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws Exception {
in = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-9"));
out = new PrintWriter(System.out);
st = new StreamTokenizer(in);
solve();
in.close();
out.close();
}
private static void solve() throws Exception {
int N = nextInt();
int[][] otr = new int[N][2];
for (int i = 0; i < N; i++) {
for (int j = 0; j < 2; j++) {
otr[i][j] = nextInt();
}
}
int allCount = 0;
int[] count = new int[N];
for (int i = 0; i < N; i++) {
int cnt = 0;
for (int j = 0; j < N; j++) {
if (i != j && (peres(otr[i], otr[j]) || peres(otr[j], otr[i])))
++cnt;
}
count[i] = cnt;
allCount += cnt;
}
ArrayList<Integer> ans = new ArrayList<Integer>();
for (int k = 0; k < N; k++) {
if (allCount == count[k] * 2)
ans.add(k);
}
out.println(ans.size());
for (int v : ans) {
out.print(v + 1);
out.print(' ');
}
}
private static boolean peres(int[] a, int[] b) {
if (a[0] == b[0] && a[1] == b[1])
return true;
return a[0] < b[0] && b[0] < a[1] || a[0] < b[1] && b[1] < a[1];
}
static StreamTokenizer st;
static BufferedReader in;
static PrintWriter out;
static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
static double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
static String nextString() throws IOException {
st.nextToken();
return st.sval;
}
} | Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 8e5540c861485655a71c3a36053c023e | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes |
import java.awt.Point;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
session[] A = new session[n];
for (int i = 0; i < n; i++)
A[i] = new session(in.nextInt(), in.nextInt(), i);
Arrays.sort(A);
boolean[] Can = new boolean[n];
int ans = 0;
for (int i = 0; i < n; i++) {
boolean bad = false;
for (int j = 1; j < i; j++)
if (A[j].s < A[j - 1].t)
bad = true;
for (int j = i + 2; j < n; j++)
if (A[j].s < A[j - 1].t)
bad = true;
if (i > 0 && i < n - 1 && A[i + 1].s < A[i - 1].t)
bad = true;
if (!bad) {
ans++;
Can[A[i].index] = true;
}
}
System.out.println(ans);
for (int i = 0; i < n; i++)
if (Can[i])
System.out.print(i + 1 + " ");
System.out.println();
}
}
class session implements Comparable<session> {
int s;
int t;
int index;
public session(int i, int j, int k) {
s = i;
t = j;
index = k;
}
public int compareTo(session o) {
if (t != o.t)
return t - o.t;
return s - o.s;
}
} | Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | b2ba0300354bd2a080c5e9be17dbb90c | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable {
class Segment implements Comparable<Segment> {
int l, r, id;
public Segment(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
@Override
public int compareTo(Segment o) {
if (l < o.l)
return -1;
if (l > o.l)
return 1;
if (r < o.r)
return -1;
if (r > o.r)
return 1;
return 0;
}
}
private void solve() throws IOException {
int n = nextInt();
Segment[] s = new Segment[n];
for (int i = 0; i < n; i++) {
s[i] = new Segment(nextInt(), nextInt(), i);
}
Arrays.sort(s);
boolean[] ok = new boolean[n];
int ans = 0;
ii: for (int i = 0; i < n; i++) {
int last = Integer.MIN_VALUE;
for (int j = 0; j < n; j++) {
if (j == i)
continue;
if (s[j].l < last)
continue ii;
last = s[j].r;
}
ok[s[i].id] = true;
ans++;
}
out.println(ans);
for (int i = 0; i < n; i++) {
if (ok[i]) {
out.print((i + 1) + " ");
}
}
}
public static void main(String[] args) {
new Thread(new C()).start();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
boolean eof = false;
public void run() {
Locale.setDefault(Locale.US);
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(239);
}
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
} | Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 315e0b5f2e75335b17c6623fd76f66ba | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ProblemC {
static class Segment implements Comparable<Segment> {
static int _seq;
int id;
int f;
int t;
Segment(String[] l) {
_seq++;
id = _seq;
f = Integer.valueOf(l[0]);
t = Integer.valueOf(l[1]);
}
@Override
public int compareTo(Segment arg0) {
if (f == arg0.f) {
return t - arg0.t;
}
return f - arg0.f;
}
}
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.valueOf(s.readLine());
Segment[] seg = new Segment[n];
for (int i = 0 ; i < n ; i++) {
seg[i] = new Segment(s.readLine().split(" "));
}
Arrays.sort(seg);
int[] imos = new int[1000100];
for (int i = 0 ; i < n ; i++) {
imos[seg[i].f]++;
imos[seg[i].t]--;
}
boolean lessthan3 = true;
for (int i = 0 ; i < 1000100 - 1 ; i++) {
imos[i+1] += imos[i];
if (imos[i+1] >= 3) {
lessthan3 = false;
break;
}
}
if (!lessthan3) {
out.println(0);
out.flush();
return;
}
int cnt = 0;
boolean[] cov = new boolean[n];
for (int i = 0 ; i < n ; i++) {
boolean isok = true;
int to = 0;
for (int j = 0 ; j < n ; j++) {
if (i == j) {
continue;
}
if (to <= seg[j].f) {
to = seg[j].t;
} else {
isok = false;
break;
}
}
if (isok) {
cov[seg[i].id-1] = true;
cnt++;
}
}
out.println(cnt);
if (cnt >= 1) {
StringBuffer b = new StringBuffer();
for (int i = 0 ; i < n ; i++) {
if (cov[i]) {
b.append(" ").append(i+1);
}
}
out.println(b.substring(1));
}
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
} | Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | fb727d19ef6cd3303948ba4b2757ccae | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main implements Runnable {
class Segment implements Comparable<Segment> {
int l, r, id;
Segment(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
public int compareTo(Segment o) {
return l - o.l;
}
}
public void _main() throws IOException {
int n = nextInt();
Segment[] s = new Segment[n];
for (int i = 0; i < n; i++)
s[i] = new Segment(nextInt(), nextInt() - 1, i);
Arrays.sort(s);
List<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (emptyIntersection(s, i))
res.add(i + 1);
}
out.println(res.size());
for (int x : res)
out.print(x + " ");
}
boolean emptyIntersection(Segment[] s, int bad) {
int x = -1;
for (Segment seg : s) {
if (seg.id == bad) continue;
if (seg.l <= x)
return false;
if (seg.r > x)
x = seg.r;
}
return true;
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 859193f6ca108127bcf74755547e0bb9 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | //package round31;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.Scanner;
public class C {
private Scanner in;
private PrintWriter out;
// private String INPUT = "3 3 10 20 30 1 3";
// private String INPUT = "4 3 10 20 30 1 3 1 39";
// private String INPUT = "3 1 5 2 6 3 7";
// private String INPUT = "2 1 4 1 4";
// private String INPUT = "3 1 4 1 4 5 6";
// private String INPUT = "3 1 4 1 4 3 6";
private String INPUT = "";
public void solve()
{
int n = ni();
Pair[] p = new Pair[n];
for(int i = 0;i < n;i++){
p[i] = new Pair(ni(), ni(), i);
}
BitSet[] bss = new BitSet[n];
for(int i = 0;i < n;i++)bss[i] = new BitSet();
for(int i = 0;i < n;i++){
for(int j = 0;j < i;j++){
if(intersect(p[i], p[j])){
bss[i].set(j);
bss[j].set(i);
}
}
}
int ct2 = 0;
int ct1 = 0;
for(int i = 0;i < n;i++){
if(bss[i].cardinality() >= 2){
ct2++;
}else if(bss[i].cardinality() == 1){
ct1++;
}
}
if(ct2 == 0){
if(ct1 == 2){
List<Integer> ll = new ArrayList<Integer>();
for(int i = 0;i < n;i++){
if(bss[i].cardinality() == 1){
ll.add(i);
if(ll.size() == 2)break;
}
}
out.println(2);
for(int i = 0;i < 2;i++){
out.print((ll.get(i)+1) + " ");
}
}else{
out.println(n);
for(int i = 1;i <= n;i++){
out.print(i + " ");
}
}
out.println();
}else if(ct2 == 1){
for(int i = 0;i < n;i++){
if(bss[i].cardinality() >= 2){
out.println(1);
out.println(i + 1);
break;
}
}
}else{
out.println(0);
}
}
public boolean intersect(Pair a, Pair b)
{
return (a.from <= b.from && b.from < a.to) || (b.from <= a.from && a.from < b.to);
}
public static class Pair
{
public int from;
public int to;
public int ind;
public Pair(int from, int to, int ind)
{
this.from = from;
this.to = to;
this.ind = ind;
}
}
public void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
private int ni() { return Integer.parseInt(in.next()); }
private void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 1595d6b72de15dc0a49bf966d293f3ce | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
private static void solve() throws Exception
{
int n = Integer.parseInt(in.readLine());
Seg[] s = new Seg[n];
for (int i = 0; i < n; i++)
{
String[] raw = in.readLine().split("\\s+");
int a = Integer.parseInt(raw[0]);
int b = Integer.parseInt(raw[1]);
s[i] = new Seg(a, b, i+1);
}
Arrays.sort(s);
int[] ans = new int[n];
int cnt = 0;
for (int i = 0; i < n; i++)
{
boolean ok = true;
for (int j = 1; j < i; j++)
{
if (s[j-1].b > s[j].a)
ok = false;
}
if (i-1 >= 0 && i+1 < s.length &&
s[i-1].b > s[i+1].a)
{
ok = false;
}
for (int j = i+2; j < n; j++)
{
if (s[j-1].b > s[j].a)
ok = false;
}
if (ok)
ans[cnt++] = s[i].th;
}
Arrays.sort(ans, 0, cnt);
out.println(cnt);
for (int i = 0; i < cnt; i++)
out.print(ans[i] + " ");
if (cnt > 0)
out.println();
}
private static class Seg implements Comparable<Seg>
{
public Seg(int a, int b, int th)
{
this.a = a;
this.b = b;
this.th = th;
}
public int compareTo(Seg other)
{
return this.a - other.a;
}
private int a;
private int b;
private int th;
}
public static void main(String[] args) throws Exception
{
long start = System.currentTimeMillis();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
long end = System.currentTimeMillis();
System.err.printf("%.3f sec%n", (end - start) / 1000.0);
}
private static BufferedReader in;
private static PrintWriter out;
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 89a8a121afc0ca9494b37567ab288806 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class C {
public static boolean intersect(int s1, int e1, int s2, int e2) {
if(s2==e1||s1==e2) return false;
if (s1 <= e2 && s1 >= s2 || s2 <= e1 && s2 >= s1)
return true;
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] st = new int[n];
int[] end = new int[n];
for (int i = 0; i < n; i++) {
st[i] = sc.nextInt();
end[i] = sc.nextInt();
}
HashSet<Integer> set = new HashSet<Integer>();
int c = 0;
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (intersect(st[i], end[i], st[j], end[j])) {
if (set.contains(i)) {
res = i;
}
if (set.contains(j)) {
res = j;
}
set.add(i);
set.add(j);
c++;
}
}
}
if (!set.isEmpty()&&set.size() != c + 1) {
System.out.println(0);
return;
}
if (set.isEmpty()) {
System.out.println(n);
for(int i=1;i<=n;i++)
System.out.print(i+" ");
} else {
if (set.size() == 2) {
System.out.println(2);
Integer[] ar=new Integer[set.size()];
set.toArray(ar);
Arrays.sort(ar);
for(Integer e:ar){
System.out.print((e+1)+" ");
}
} else {
System.out.println(1);
System.out.println(res+1);
}
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 8f3a44491dc8371ed2a74a0c1ac5362c | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes |
import java.io.*;
import java.util.*;
public class CodeForce {
private void solve() throws IOException {
int N = nextInt();
int []L = new int[N + 1];
int []R = new int[N + 1];
for(int i = 0; i < N; i++) {
L[i] = nextInt();
R[i] = nextInt();
}
int []T = new int[N + 1];
int ans = 0;
for(int i = 1; i < N; i++) {
for(int j = 0; j < i; j++) {
if(L[i] < R[j] && R[i] > L[j]) {
T[i]++;
T[j]++;
ans++;
}
}
}
int M = 0;
int []S = new int[N+1];
for(int i = 0; i < N; i++) {
if(T[i] == ans) {
S[M++] = i + 1;
}
}
System.out.println(M);
for(int i = 0; i < M; i++) {
System.out.print(S[i] + " ");
}
}
public static void main(String[] args) {
new CodeForce().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(new FileOutputStream(new File("output.txt")));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 35afca63c658a5efb8200c842124f543 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Schedule {
/**
* @param args
*/
static class Section {
int left;
int right;
int index;
static boolean isIntersect(Section a, Section b) {
if (a.right > b.left) {
return true;
}
else {
return false;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
while(cin.hasNext()) {
int n = cin.nextInt();
Section[] ln = new Section[n];
for (int i = 0; i < n; i++) {
ln[i] = new Section();
ln[i].left = cin.nextInt();
ln[i].right = cin.nextInt();
ln[i].index = i + 1;
}
Arrays.sort(ln, new Comparator<Section>() {
@Override
public int compare(Section o1, Section o2) {
// TODO Auto-generated method stub
if (o1.left == o2.left) {
return o1.right - o2.right;
}
else {
return o1.left - o2.left;
}
}
});
List<Integer> out = new ArrayList<Integer>();
for (int i = 0; i < ln.length; i++) {
boolean intersect = false;
Section pre = ln[0];
for (int j = 1; j < ln.length; j++) {
if (i != j) {
if (Section.isIntersect(pre, ln[j])) {
intersect = true;
break;
}
pre = ln[j];
}
}
if (intersect == false) {
out.add(ln[i].index);
}
}
Collections.sort(out);
System.out.println(out.size());
final Integer[] temp = out.toArray(new Integer[0]);
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1) {
System.out.println(temp[i]);
}
else {
System.out.print(temp[i] + " ");
}
}
}
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | f211ee0323e749bfd87a6407d2d7f90e | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
new C().run();
}
static class Pair {
int index;
Range range;
Pair(int index, Range range) {
this.index = index;
this.range = range;
}
}
static class Range {
int start, end;
Range(int start, int end) {
this.start = start;
this.end = end;
}
boolean intersect(Range r) {
return (start <= r.start && r.start < end) ||
(start < r.end && r.end <= end);
}
}
private void run() {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
ArrayList<Pair> list = new ArrayList<Pair>(n);
for(int i = 0; i < n; i++) {
list.add(new Pair(i, new Range(s.nextInt(), s.nextInt())));
}
Collections.sort(list, new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
if( o1.range.start != o2.range.start)
return o1.range.start - o2.range.start;
return o1.range.end - o2.range.end;
}
});
ArrayList<Integer> res = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++) {
ArrayList<Pair> rlist = new ArrayList<Pair>(list);
rlist.remove(i);
boolean success = true;
for(int j = 0; j < rlist.size()-1; j++) {
Range r1 = rlist.get(j).range;
Range r2 = rlist.get(j+1).range;
if(r1.intersect(r2)) {
success = false;
break;
}
}
if(success) {
res.add(list.get(i).index+1);
}
}
Collections.sort(res);
System.out.println(res.size());
for(int index : res) {
System.out.printf("%d ", index);
}
System.out.println();
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 96323922cc9153d4b691cda828e0b0e3 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
static class dat
{
int ind = 0;
int beg = 0;
int end = 0;
}
static dat dats[];
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
boolean us[] = new boolean[n];
dats = new dat[n];
for(int i = 0;i<n;i++)
{
dats[i] = new dat();
dats[i].beg = scan.nextInt();
dats[i].end = scan.nextInt();
dats[i].ind = i;
}
quickSort(0,n-1);
int cols = 0;
int ind = -1;
int ind1 = -1;
for(int i = 1;i<n;i++)
{
int prevend = dats[i-1].end;
if(dats[i].beg<prevend)
{
if(cols==1)
{
System.out.print(0);
return;
}
if(i==n-1||(dats[i].end<=dats[i+1].beg&&dats[i-1].end<=dats[i+1].beg))
{
ind = dats[i-1].ind+1;
ind1 = dats[i].ind+1;
}
else
if(dats[i].end>dats[i-1].end)
{
int temp = dats[i].end;
dats[i].end = dats[i-1].end;
dats[i-1].end = temp;
ind = dats[i].ind+1;
}
else
{
ind = dats[i-1].ind+1;
}
cols++;
}
}
if(cols==0)
{
System.out.println(n);
for(int i = 1;i<=n;i++)
{
System.out.print(i+" ");
}
}
else
{
if(ind1<0)
{
System.out.println(1);
System.out.println(ind);
}
else
{
System.out.println(2);
if(ind>ind1)
{
System.out.print(ind1+" "+ind);
}
else
{
System.out.print(ind+" "+ind1);
}
}
}
}
static void quickSort(int begin,int end)
{
int i=begin;
int j=end;
int m=i+(j-i)/2;
int mid=dats[m].beg;
do
{
while (dats[i].beg < mid)
i++;
while (dats[j].beg > mid)
j--;
if(j>=i)
{
dat temp;
temp=dats[j];
dats[j]=dats[i];
dats[i]=temp;
// dats[i].ind=i;
// dats[j].ind=j;
i++;
j--;
}
}
while(i<=j);
if(j>begin) quickSort(begin,j);
if(end>i)quickSort(i,end);
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 615bb614970bcb51ecfed0f7fb47dab7 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
static class Pair implements Comparable<Pair> {
int l, r;
int idx;
public Pair(int l, int r, int idx) {
super();
this.l = l;
this.r = r;
this.idx = idx;
}
@Override
public String toString() {
return "Pair [l=" + l + ", r=" + r + ", idx=" + idx + "]";
}
@Override
public int compareTo(Pair o) {
if (l != o.l)
return l - o.l;
return r - o.r;
}
}
void solve() throws IOException {
int n = ni();
Pair[] v = new Pair[n];
for (int i = 0; i < n; ++i)
v[i] = new Pair(ni(), ni(), i);
Arrays.sort(v);
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int it = 0; it < n; ++it) {
int pred = 0;
while (pred == it)
++pred;
boolean ok = true;
for (int i = 0; i < n; ++i)
if (i > pred && i != it) {
ok &= v[i].l >= v[pred].r;
pred = i;
}
if (ok)
ret.add(v[it].idx + 1);
}
Collections.sort(ret);
out.println(ret.size());
for (int a : ret)
out.print(a + " ");
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | 1a54a4657df6488cb611263ce0d16904 | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int MAX = 1000000;
int N;
Range[] rng;
Event[] event;
RMQ rmq;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
N = nextInt();
rng = new Range [N];
event = new Event [2 * N];
for (int i = 0; i < N; i++) {
rng[i] = new Range(i + 1, nextInt() - 1, nextInt() - 1);
event[2 * i] = new Event(1, rng[i].l + 1);
event[2 * i + 1] = new Event(-1, rng[i].r);
}
sort(event);
// System.out.println(Arrays.toString(event));
int[] cnt = new int [MAX];
int pnt = 0;
int bal = 0;
for (int x = 0; x < MAX; x++) {
while (pnt < 2 * N && event[pnt].pos == x && event[pnt].type == 1) {
bal++;
pnt++;
}
cnt[x] = bal;
while (pnt < 2 * N && event[pnt].pos == x) {
bal--;
pnt++;
}
}
rmq = new RMQ(cnt);
List<Range> ans = new ArrayList<Main.Range>(N);
for (Range r : rng)
if (rmq.get(r.l, r.r) < 3 && rmq.get(0, r.l - 1) < 2 && rmq.get(r.r + 1, MAX - 1) < 2)
ans.add(r);
out.println(ans.size());
if (ans.size() > 0) {
for (int i = 0; i < ans.size(); i++) {
if (i > 0)
out.print(' ');
out.print(ans.get(i).id);
}
out.println();
}
out.close();
}
class RMQ {
int n;
int[] a;
RMQ(int[] v) {
n = v.length;
a = new int [2 * n];
for (int i = 0; i < n; i++)
a[n + i] = v[i];
for (int i = n - 1; i > 0; i--)
a[i] = max(a[2 * i], a[2 * i + 1]);
}
int get(int l, int r) {
l += n; r += n;
int ret = Integer.MIN_VALUE;
while (l <= r) {
if (l % 2 == 1) ret = max(ret, a[l]);
if (r % 2 == 0) ret = max(ret, a[r]);
l = (l + 1) / 2;
r = (r - 1) / 2;
}
return ret;
}
}
class Range implements Comparable<Range> {
int id;
int l;
int r;
Range(int id, int l, int r) {
this.id = id;
this.l = l;
this.r = r;
}
@Override
public int compareTo(Range rng) {
if (l != rng.l)
return l - rng.l;
return r - rng.r;
}
@Override
public String toString() {
return String.format("(id = %d, l = %d, r = %d)", id, l, r);
}
}
class Event implements Comparable<Event> {
int type;
int pos;
Event(int type, int pos) {
this.type = type;
this.pos = pos;
}
@Override
public int compareTo(Event e) {
if (pos != e.pos)
return pos - e.pos;
return e.type - type;
}
@Override
public String toString() {
return String.format("(%d, %d)", type, pos);
}
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return true;
}
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | b5914a6acc94733e45976bb2be99189c | train_001.jsonl | 1285599600 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. | 256 megabytes |
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import static java.lang.Integer.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class round31C {
static class state implements Comparable<state>{
int start, end, idx;
public state(int st, int en, int i){
start = st;
end = en;
idx = i;
}
public int compareTo(state s){
if(this.end < s.end)
return -1;
if(this.end > s.end)
return 1;
if(this.start < s.start)
return -1;
if(this.start > s.start)
return 1;
return 0;
}
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = parseInt(br.readLine());
String [] use = null;
state [] lessons = new state [n];
for(int i = 0 ; i < n ; ++i){
use = br.readLine().split(" ");
int st = parseInt(use[0]);
int end = parseInt(use[1]);
lessons[i] = new state(st, end, i + 1);
}
Arrays.sort(lessons);
LinkedList<Integer> ans = new LinkedList<Integer>();
for(int i = 0 ; i < lessons.length ; ++i){//try removing i
int maxEnd = -(int)1e9;
boolean f = true;
for(int j = 0 ; j < lessons.length ; ++j){
if(i == j)
continue;
if(lessons[j].start < maxEnd){
f = false;
break;
}else{
maxEnd = lessons[j].end;
}
}
if(f)
ans.add(lessons[i].idx);
}
System.out.println(ans.size());
int [] out = new int [ans.size()];
int m = 0;
for(Integer i : ans)
out[m++] = i;
Arrays.sort(out);
for(int i = 0 ; i < out.length ; ++i)
System.out.print(out[i] + " ");
}
}
| Java | ["3\n3 10\n20 30\n1 3", "4\n3 10\n20 30\n1 3\n1 39", "3\n1 5\n2 6\n3 7"] | 2 seconds | ["3\n1 2 3", "1\n4", "0"] | null | Java 6 | standard input | [
"implementation"
] | df28bb63a627a41d67f02cbd927d5e9a | The first line contains integer n (1ββ€βnββ€β5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1ββ€βliβ<βriββ€β106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). | 1,700 | Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. | standard output | |
PASSED | c3e042b81719eecf521efb38e876cf90 | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Problem {
public static void main(String[] arg) {
FastScanner scan = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
int arr[][] = new int[n+1][2];
int min = 10001, max = -10001;
for(int i = 0; i < n; i++){
int a = scan.nextInt();
int b = scan.nextInt();
if(a > b){
int t = a;
a = b;
b = t;
}
min = Math.min(min, a);
max = Math.max(max, b);
arr[i][0] = a;
arr[i][1] = b;
}
boolean used[] = new boolean[n+1];
List<Integer> rets = new ArrayList<Integer>();
for(int i = min; i <= max + 1; i++){
boolean possible = true;
for(int j = 0; j < n; j++){
if(used[j]) continue;
if(arr[j][1] < i){
possible = false;
break;
}
}
if(!possible){
for(int j = 0; j < n; j++){
if(arr[j][0] <= i-1 && i-1 <= arr[j][1]){
used[j] = true;
}
}
rets.add(i-1);
}
}
out.println(rets.size());
for(Integer i : rets){
out.print(i + " ");
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
try {
br = new BufferedReader(new InputStreamReader(is));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.valueOf(next());
}
}
}
| Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | 385d9884dc88ffb871ae71b963a61278 | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.util.PriorityQueue;
import java.util.Scanner;
public class d22 {
static class P implements Comparable<P> {
int from, to;
public P(int a, int b) {
this.from = Math.min(a, b);
this.to = Math.max(a, b);
}
@Override
public int compareTo(P o) {
return from - o.from;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PriorityQueue<P> starts = new PriorityQueue<P>();
PriorityQueue<Integer> ends = new PriorityQueue<Integer>();
int n = in.nextInt();
int nails = 0;
while (n-- > 0)
starts.add(new P(in.nextInt(), in.nextInt()));
StringBuilder derp = new StringBuilder();
while (starts.size() > 0) {
P here = starts.poll();
if (ends.size() > 0 && ends.peek() < here.from) {
nails++;
derp.append(ends.peek());
derp.append(' ');
ends.clear();
}
ends.add(here.to);
}
if (ends.size() > 0) {
nails++;
derp.append(ends.peek());
}
System.out.println(nails);
System.out.println(derp.toString());
}
}
| Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | 2aeb2b2ad0d8900451836353c85f7605 | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Stack;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Erasyl Abenov
*
*
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
try (PrintWriter out = new PrintWriter(outputStream)) {
TaskB solver = new TaskB();
solver.solve(1, in, out);
}
}
}
class TaskB {
class Point implements Comparable<Point>{
int start;
int end;
public Point(int start, int end){
this.start = start;
this.end = end;
}
@Override
public int compareTo(Point o){
if(o.start != start) return start - o.start;
return end - o.end;
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{
int n = in.nextInt();
Point p[] = new Point[n];
for(int i = 0; i < n; ++i){
int s = in.nextInt();
int f = in.nextInt();
if(s > f){
int tmp = f;
f = s;
s = tmp;
}
p[i] = new Point(s, f);
}
Arrays.sort(p);
Stack<Integer> st = new Stack();
st.add(p[0].end);
for(int i = 0; i < n; ++i){
if(p[i].end < st.lastElement()){
st.pop();
st.add(p[i].end);
}
else if(p[i].start > st.lastElement())
st.add(p[i].end);
}
out.println(st.size());
for(int coord : st){
out.print(coord);
out.print(" ");
}
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public BigInteger nextBigInteger(){
return new BigInteger(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | 1c2e6d64fcbf3060eac220011e876b0f | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.util.*;
import java.io.*;
public class D0022 {
public static void main(String args[]) throws Exception {
new D0022();
}
D0022() throws Exception {
PandaScanner sc = null;
PrintWriter out = null;
try {
sc = new PandaScanner(System.in);
out = new PrintWriter(System.out);
} catch (Exception ignored) {
}
int n = sc.nextInt();
ArrayList<int[]> s = new ArrayList<int[]>();
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
s.add(new int[] {Math.min(a, b), Math.max(a, b)});
}
Collections.sort(s, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return Integer.compare(a[1], b[1]);
}
});
int nails = 0;
ArrayList<Integer> locations = new ArrayList<Integer>();
while (!s.isEmpty()) {
nails++;
int loc = s.get(0)[1];
locations.add(loc);
Iterator<int[]> i = s.iterator();
while (i.hasNext()) {
int[] a = i.next();
if (loc >= a[0] && loc <= a[1]) {
i.remove();
}
}
}
out.println(nails);
out.println(locations.toString().replaceAll("[^- 0-9]", ""));
out.close();
System.exit(0);
}
//The PandaScanner class, for Panda fast scanning!
public class PandaScanner {
BufferedReader br;
StringTokenizer st;
InputStream in;
PandaScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String next() throws Exception {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
return next();
}
return st.nextToken();
}
public boolean hasNext() throws Exception {
return (st != null && st.hasMoreTokens()) || in.available() > 0;
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
}
| Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | 5662aa5961a3a13df3ca133079775f94 | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.util.*;
import java.awt.Point;
public class Segments {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
Point array[]=new Point[n];
for(int i=0;i<n;i++){
int a=in.nextInt();
int b=in.nextInt();
array[i]=new Point(Math.min(a,b),Math.max(a,b));
}
Arrays.sort(array,new solver());
StringBuilder str=new StringBuilder(array[0].y+" ");
int cur=array[0].y;
int ans=1;
for(int i=1;i<n;i++){
if(array[i].x>cur){
ans++;
str.append(array[i].y+" ");
cur=array[i].y;
}
}
System.out.println(ans);
System.out.print(str);
}
static class solver implements Comparator<Point>{
public int compare(Point a,Point b){
if(a.y==b.y)
return b.x-a.x;
return a.y-b.y;
}
}
} | Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | 0aa72d0736b2600370b8b7feddc850e8 | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.io.*;
import java.util.*;
public class D22 {
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
Pair[] data = new Pair[n];
for(int i = 0; i<n; i++) data[i] = new Pair(input.nextInt(), input.nextInt());
Arrays.sort(data);
ArrayList<Integer> res = new ArrayList<Integer>();
int last = -1111111;
for(int i = 0; i<n; i++)
{
if(data[i].a > last)
{
res.add(data[i].b);
last = data[i].b;
}
}
out.println(res.size());
for(int x : res) out.print(x+" ");
out.close();
}
static class Pair implements Comparable<Pair>
{
int a, b;
public Pair(int aa, int bb)
{
a = aa; b = bb;
if(a > b)
{
int temp = a; a = b; b = temp;
}
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return b - o.b;
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output | |
PASSED | d76bea95a185d49895215b082f74adfe | train_001.jsonl | 1277823600 | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down? | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class D21 {
private int nailsCount;
private ArrayList<Integer[]> pos = new ArrayList<>();
private int[] overlaps;
private ArrayList<Integer[]> ip = new ArrayList<Integer[]>();
public static void main(String[] args) {
D21 obj = new D21();
obj.init();
obj.compute();
obj.printOP();
}
private void init() {
Scanner scn = new Scanner(System.in);
int ipSize = scn.nextInt();
for (int i = 0; i < ipSize; i++) {
int fi = scn.nextInt();
int si = scn.nextInt();
Integer[] temp = new Integer[2];
if(fi > si)
{
temp[0] = si;
temp[1] = fi;
}
else
{
temp[0] = fi;
temp[1] = si;
}
ip.add(temp);
}
//overlaps = new int[max + 1];
}
private void compute() {
ArrayList<Integer[]> sortedIP = sortOnEnd(ip);
ArrayList<Integer[]> merged = new ArrayList<>();
merged.add(sortedIP.get(0));
for(int i = 1; i < sortedIP.size(); i++)
{
Integer[] prev = merged.get(merged.size() - 1);
Integer[] elem = sortedIP.get(i);
if(prev[0] <= elem[0] &&
prev[1] >= elem[0])
{
Integer[] temp = new Integer[2];
temp[0] = elem[0];
temp[1] = prev[1];
merged.set(merged.size()-1, temp);
}
else if(prev[1] < elem[0])
{
merged.add(elem);
}
}
pos = merged;
}
private ArrayList<Integer[]> sortOnEnd(ArrayList<Integer[]> ip) {
if(ip.size() == 1)
{
return ip;
}
else
{
ArrayList<Integer[]> lftArr = sortOnEnd(new ArrayList<Integer[]>(ip.subList(0, ip.size()/2)));
ArrayList<Integer[]> rytArr = sortOnEnd(new ArrayList<Integer[]>(ip.subList(ip.size()/2, ip.size())));
return mergeAL(lftArr, rytArr);
}
}
private ArrayList<Integer[]> mergeAL(ArrayList<Integer[]> lftArr, ArrayList<Integer[]> rytArr)
{
ArrayList<Integer[]> result = new ArrayList<>();
while( lftArr.size() > 0
|| rytArr.size() > 0)
{
if(lftArr.size() > 0
&& rytArr.size() > 0)
{
if(lftArr.get(0)[1] > rytArr.get(0)[1])
{
result.add(rytArr.remove(0));
}
else
result.add(lftArr.remove(0));
}
else if(lftArr.size() > 0)
{
result.add(lftArr.remove(0));
}else if(rytArr.size() > 0)
{
result.add(rytArr.remove(0));
}
}
return result;
}
private void printOP() {
System.out.println(pos.size());
for(Integer[] i : pos)
{
System.out.print(i[0]+" ");
}
}
}
| Java | ["2\n0 2\n2 5", "5\n0 3\n4 2\n4 8\n8 10\n7 7"] | 1 second | ["1\n2", "3\n7 10 3"] | null | Java 7 | standard input | [
"sortings",
"greedy"
] | 60558a2148f7c9741bb310412f655ee4 | The first line of the input contains single integer number n (1ββ€βnββ€β1000) β amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points. | 1,900 | The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.