exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
2e27a7045846b86f20684f1f2f65e20e
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.*; public class elections { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); int n, m, bcan=0, psi=0; int[] can=new int[101]; n=in.nextInt(); m=in.nextInt(); int i, j, a; for(i=0; i<m; i++) { int o=0, kalo=0; for(j=0; j<n; j++) { a=in.nextInt(); if(o<a || o==a && j<kalo) { kalo=j; o=a; } } can[kalo]++; } int poli=0; for(i=0; i<n; i++) if(can[poli]<can[i]) poli=i; /*for(i=0; i<n; i++) System.out.print(can[i]+" ");*/ System.out.println((poli+1)); in.close(); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≀ n, m ≀ 100) β€” the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≀ j ≀ n, 1 ≀ i ≀ m, 0 ≀ aij ≀ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number β€” the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
b9d7f3cfef5204e097fd4a139d0592dd
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
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.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class dpProblem2 { static int dp[][]; static boolean dpB[][][]; static int mods[]; static String n; static ArrayList<Integer> array = new ArrayList<>(); public static int rec(int i, int needed) { if (i == 0 && needed == 0) { return 0; } else if (i == 0 && needed != 0) { return -1; } int taken = 0; int notTaken = 0; if (dp[i - 1][((needed + 3 - mods[i]) % 3)] == -2) { taken = rec(i - 1, ((needed + 3 - mods[i]) % 3)); // dp[i-1][((needed+3 - mods[i]) % 3)] =taken; } else taken = dp[i - 1][((needed + 3 - mods[i]) % 3)]; if (dp[i - 1][needed] == -2) { notTaken = rec(i - 1, needed); // dp[i-1][needed] = notTaken; } else notTaken = dp[i - 1][needed]; if (taken >= 0 || notTaken >= 0) if (taken >= notTaken) { if (taken == 0 && n.charAt(i - 1) == '0') { dp[i][needed] = notTaken; return notTaken; } dp[i][needed] = taken + 1; array.add(i); return 1 + taken; } else { dp[i][needed] = notTaken; return notTaken; } else { dp[i][needed] = -1; return -1; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = br.readLine(); boolean[] answer = new boolean[n.length()]; Arrays.fill(answer, true); mods = new int[n.length() + 1]; int sum = 0; for (int i = 0; i < n.length(); i++) { int digit = n.charAt(i) - '0'; sum += digit; mods[i + 1] = digit % 3; } mods[0] = 0; int rem = sum % 3; dp = new int[n.length() + 1][3]; for (int i = 0; i < dp.length; i++) for (int j = 0; j < 3; j++) { dp[i][j] = -2; } int size = rec(n.length(), 0); int tmpSize = size; // System.out.println(size); StringBuilder s = new StringBuilder(); int currentSum = 0; int lastOne = tmpSize + 1; int needed = 0; int count = 0; boolean flag = false; boolean start = true; int last = -1; // for (int i = dp.length - 1; i >= 0; i--) // System.out.println(dp[i][0] + " " + dp[i][1] + " " + dp[i][2]); for (int i = dp.length - 1; i >= 0; i--) { int tmpNeeded = (3 - currentSum % 3) % 3; int tmp =dp[i][tmpNeeded]; while ( i >= 1 && dp[i-1][tmpNeeded] == tmp ) { flag = true; i--; } // if (flag) { // i++; // flag = false; // } // start = false; needed = (3 - currentSum % 3) % 3; if (dp[i][needed] == lastOne - 1 && dp[i][needed] > 0){ s.insert(0, n.charAt(i - 1) + ""); count++; }else{ if(count < tmpSize){ continue; }else break; } last = lastOne; lastOne--; currentSum += Integer.parseInt(n.charAt(i - 1) + ""); } boolean zero = false; for (int i = 0; i < n.length(); i++) if (n.charAt(i) == '0') { zero = true; break; } if (s.toString().equals("") && zero) System.out.println(0); else if (s.toString().equals("")) System.out.println("-1"); else System.out.println(s); } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
8373064b0b80315aa23ebe26e7484a34
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.util.*; public class DivideByThree { public static void main(String[] args) { Scanner in = new Scanner(System.in); String num_str= in.next(); char[] num = num_str.toCharArray(); int sum = 0; List<Integer> ones = new ArrayList<Integer>(); List<Integer> twos = new ArrayList<Integer>(); int idx = num.length - 1; while (idx >= 0) { int mod = (num[idx] - '0') % 3; if (mod == 1) { sum += 1; if(ones.size() < 2) ones.add(idx); } else if (mod == 2) { sum += 2; if (twos.size() < 2) twos.add(idx); } idx--; } if (sum % 3 == 0) { System.out.print(num); return; } //only need to know the top four options at most Integer ans1 = ones.isEmpty() ? null : ones.remove(0); Integer ans1_ = ones.isEmpty() ? null: ones.remove(0); Integer ans2 = twos.isEmpty() ? null : twos.remove(0); Integer ans2_ = twos.isEmpty() ? null : twos.remove(0); if (sum % 3 == 1) { String a = removeSingle(ans1, num_str); String b = removeDouble(ans2, ans2_, num_str); if (a.length() == 0 && b.length() == 0) { System.out.print(-1); } else if (a.length() == 0) { System.out.print(b); } else if (b.length() == 0) { System.out.print(a); } else { System.out.print((a.length() > b.length() ? a : b)); } } else { String a = removeSingle(ans2, num_str); String b = removeDouble(ans1, ans1_, num_str); if (a.length() == 0 && b.length() == 0) { System.out.print(-1); } else if (a.length() == 0) { System.out.print(b); } else if (b.length() == 0) { System.out.print(a); } else { System.out.print((a.length() > b.length() ? a : b)); } } } public static String trim(String s) { if (s.length() == 0) return ""; int i = 0; while (i < s.length() && s.charAt(i) == '0') { i++; } if (i == s.length()) return "0"; else return s.substring(i, s.length()); } public static String removeSingle(Integer pos, String s) { if (pos == null) return ""; s = s.substring(0, pos) + (pos + 1 == s.length() ? "" : s.substring(pos + 1, s.length())); return trim(s); } public static String removeDouble(Integer pos, Integer pos_, String s) { if (pos_ == null) return ""; s = s.substring(0, pos_) + s.substring(pos_ + 1, pos) + (pos + 1 == s.length() ? "" : s.substring(pos + 1, s.length())); return trim(s); } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
d768bfce9af75d420a183aa66bed729a
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.util.*; public class DivideByThree { public static void main(String[] args) { Scanner in = new Scanner(System.in); String num_str= in.next(); char[] num = num_str.toCharArray(); int sum = 0; List<Integer> ones = new ArrayList<Integer>(); List<Integer> twos = new ArrayList<Integer>(); int idx = num.length - 1; while (idx >= 0) { int mod = (num[idx] - '0') % 3; if (mod == 1) { sum += 1; ones.add(idx); } else if (mod == 2) { sum += 2; twos.add(idx); } idx--; } if (sum % 3 == 0) { System.out.print(num); return; } //only need to know the top four options at most Integer ans1 = ones.isEmpty() ? null : ones.remove(0); Integer ans1_ = ones.isEmpty() ? null: ones.remove(0); Integer ans2 = twos.isEmpty() ? null : twos.remove(0); Integer ans2_ = twos.isEmpty() ? null : twos.remove(0); if (sum % 3 == 1) { String a = removeSingle(ans1, num_str); String b = removeDouble(ans2, ans2_, num_str); if (a.length() == 0 && b.length() == 0) { System.out.print(-1); } else if (a.length() == 0) { System.out.print(b); } else if (b.length() == 0) { System.out.print(a); } else { System.out.print((a.length() > b.length() ? a : b)); } } else { String a = removeSingle(ans2, num_str); String b = removeDouble(ans1, ans1_, num_str); if (a.length() == 0 && b.length() == 0) { System.out.print(-1); } else if (a.length() == 0) { System.out.print(b); } else if (b.length() == 0) { System.out.print(a); } else { System.out.print((a.length() > b.length() ? a : b)); } } } public static String trim(String s) { if (s.length() == 0) return ""; int i = 0; while (i < s.length() && s.charAt(i) == '0') { i++; } if (i == s.length()) return "0"; else return s.substring(i, s.length()); } public static String removeSingle(Integer pos, String s) { if (pos == null) return ""; s = s.substring(0, pos) + (pos + 1 == s.length() ? "" : s.substring(pos + 1, s.length())); return trim(s); } public static String removeDouble(Integer pos, Integer pos_, String s) { if (pos_ == null) return ""; s = s.substring(0, pos_) + s.substring(pos_ + 1, pos) + (pos + 1 == s.length() ? "" : s.substring(pos + 1, s.length())); return trim(s); } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
32b9bdb881eae4d2402d48d697b8a667
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.io.PrintWriter; import java.lang.reflect.Array; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.Stack; import java.util.ArrayList; import java.util.Arrays; import java.lang.*; public class tester { 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; } } static class item implements Comparable<item> { int current; int later; int dif; public int compareTo(item c) { return this.dif -c.dif; } } //-----------------------mycode--------------------------------------------------------------------------- public static void main(String args[]) { FastReader sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); String s=sc.nextLine(); ArrayList<Integer> arr=new ArrayList<>(); int sum=0; int count=0,count1=0; boolean flag=false,flag2=false,flag3=false; for(int i=0;i<s.length();i++) { arr.add((s.charAt(i)-'0')%3); sum+=arr.get(i); sum=sum%3; } //out.println("sum="+sum); String s1=null,s2=null; if(sum==1) { count=arr.lastIndexOf(1); if(count!=-1) { s1=s.substring(0,count)+s.substring(count+1,s.length()); while(!(s1.isEmpty()) && s1.charAt(0)=='0') { s1=s1.substring(1,s1.length()); flag=true; } if(s1.isEmpty()&&flag) s1+='0'; flag=false; flag2=true; } count1=arr.lastIndexOf(2); if(count1!=-1) {arr.remove(count1); arr.add(count1,-1);} count=arr.lastIndexOf(2); //out.println(count+" "+count1); if(count!=-1 &&count1!=-1) { flag3=true; s2=s.substring(0,count)+s.substring(count+1,count1)+s.substring(count1+1,s.length()); if(flag2) s=s1; while(!(s2.isEmpty()) && s2.charAt(0)=='0') { s2=s2.substring(1,s2.length()); flag=true; } if(s2.isEmpty()&&flag) s2+='0'; if(flag2) { if(s.length()<s2.length()) s=s2; } else s=s2; } if(!flag3 && flag2) s=s1; } else if(sum==2) { count=arr.lastIndexOf(2); //out.print(count); if(count!=-1) { s1=s.substring(0,count)+s.substring(count+1,s.length()); while(!s1.isEmpty()&&s1.charAt(0)=='0') { s1=s1.substring(1,s1.length()); flag=true; } if(s1.isEmpty()&&flag) s1+='0'; flag=false; flag2=true; } //out.println(s1); count1=arr.lastIndexOf(1); if(count1!=-1) {arr.remove(count1); arr.add(count1,-1);} count=arr.lastIndexOf(1); //out.println(count+" "+count1); out.flush(); if(count!=-1 &&count1!=-1) { flag3=true; s2=s.substring(0,count)+s.substring(count+1,count1)+s.substring(count1+1,s.length()); if(flag2) s=s1; while(!s2.isEmpty()&&s2.charAt(0)=='0') { s2=s2.substring(1,s2.length()); flag=true; } if(s2.isEmpty()&&flag) s2+='0'; if(flag2) { if(s.length()<s2.length()) s=s2; } else s=s2; } if(!flag3 && flag2) s=s1; } if(s.isEmpty()) out.println(-1); else {while(!s.isEmpty()&&s.charAt(0)=='0') { s=s.substring(1,s.length()); flag=true; } if(s.isEmpty()&&flag) s+='0'; out.println(s); } out.close(); } //---------------------------end of code----------------------------------------------------------------- }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
3650b7fe6e3b91e667660fe5c0d3a2b7
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.util.Scanner; public class R792C { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s=in.next(); int[] m=new int[3]; for(int i=1; i<3; i++) m[i]=0; int sum=0; boolean zero=false; for(int i=0; i<s.length(); i++) { int c = s.charAt(i)-'0'; if (c==0) zero=true; else if (c%3!=0) m[c%3]++; sum+=c; } if (sum % 3==0) System.out.println(s); else if (m[sum%3]==0 && m[(2*(sum%3))%3]<2) { if (zero) System.out.println(0); else System.out.println(-1); } else { String[] ans=new String[3]; for(int i=1; i<=2; i++) { ans[i]=s; int count = (sum%3==i) ? 1 : 2; if (m[i]<count) { ans[i]=""; continue; } int pos = s.length() - 1; while (count > 0) { if ((ans[i].charAt(pos) - '0') % 3 == i) { ans[i] = new StringBuilder(ans[i]).deleteCharAt(pos).toString(); count--; } pos--; } pos=0; while(pos<ans[i].length() && ans[i].charAt(pos)=='0') pos++; if (pos==ans[i].length() && pos!=0) ans[i]="0"; else ans[i]=ans[i].substring(pos); } s=(ans[1].length()>ans[2].length())? ans[1]:ans[2]; if (s.length()==0) System.out.println(-1); else System.out.println(s); } } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
bbbf0d3d39cc7e281ede83689095e0ba
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Chiaki.Hoshinomori */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { char[] s = in.next().toCharArray(); int n = s.length; int[] last = new int[]{-1, -1, -1}; int[][] dp = new int[n][]; int[][] pv = new int[n][]; boolean zero = false; for (int i = 0; i < n; i++) { dp[i] = new int[]{-1, -1, -1}; pv[i] = new int[]{-1, -1, -1}; int now = (s[i] - '0') % 3; for (int j = 0; j < 3; ++j) { if (last[j] != -1) { dp[i][(j + now) % 3] = dp[last[j]][j] + 1; pv[i][(j + now) % 3] = last[j]; } } if (s[i] == '0') zero = true; if (s[i] != '0' && dp[i][now] == -1) { dp[i][now] = 1; } for (int j = 0; j < 3; ++j) { if (dp[i][j] != -1 && (last[j] == -1 || dp[i][j] > dp[last[j]][j])) { last[j] = i; } } } if (last[0] == -1) { if (zero) out.println(0); else out.println(-1); } else { char[] t = new char[dp[last[0]][0]]; for (int i = t.length - 1, p = last[0], v = 0; p != -1; --i) { t[i] = s[p]; int e = pv[p][v]; v = (v - (s[p] - '0') % 3 + 3) % 3; p = e; } out.println(new String(t)); } } } 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(); } } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
141565791b539140d271fe3cbf482c7f
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); StringBuilder sb1 = new StringBuilder(s), sb2 = new StringBuilder(s); char num[] = s.toCharArray(); int sum=0; for(char c : num){ int t=c-'0'; sum+=t%3; } if(sum%3==0) System.out.print(s); else if(sum%3==1){ boolean one ,two; one = method(sb1,1,1); two = method(sb2,2,2); if(one && two) System.out.print(sb1.length()>sb2.length() ? sb1 :sb2); else if(one) System.out.print(sb1); else if(two) System.out.print(sb2); else System.out.print(-1); } else{ boolean one ,two; one = method(sb1,2,1); two = method(sb2,1,2); if(one && two) System.out.print(sb1.length()>sb2.length() ? sb1 :sb2); else if(one) System.out.print(sb1); else if(two) System.out.print(sb2); else System.out.print(-1); } } static boolean method(StringBuilder sb , int n, int count){ for(int i=sb.length()-1 ; i>=0 ;i--){ if((sb.charAt(i)-'0')%3==n){ sb.deleteCharAt(i); count--; if(count==0) break; } } if(sb.length()==0) return false; while(sb.charAt(0)=='0' && sb.length()>1){ sb.deleteCharAt(0); } if(count==0 && sb.length()>0) return true; return false; } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
5be213032509b961adcdc22f67e5f44c
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { private static int n; private static Integer dp[][][]; private static int p[][][]; private static String s; private static StringBuilder ans = new StringBuilder(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); s = sc.next(); n = s.length(); dp = new Integer[n][3][2]; p = new int[n][3][2]; int res = dp(0,0,0); if(res >= (int)1e9) { for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == '0') { System.out.println('0'); return; } } System.out.println(-1); return; } print(0,0,0); System.out.println(ans); out.flush(); } private static int dp(int i,int mod,int x) { if(i == n) { if(mod == 0 && x == 1) return 0; return (int)1e9; } if(dp[i][mod][x] != null) return dp[i][mod][x]; int c1 = dp(i+1,mod,x) + 1; int c2 = (int)1e9; // we want to minimize this if(x > 0 || s.charAt(i) != '0') c2 = dp(i + 1,(mod%3+(s.charAt(i)-'0')%3)%3,1); if(c1 < c2) { dp[i][mod][x] = c1; p[i][mod][x] = 1; }else { dp[i][mod][x] = c2; p[i][mod][x] = 2; } return dp[i][mod][x]; } private static void print(int i,int mod,int r) { if(i == n) return; if(p[i][mod][r] == 2) { ans.append(s.charAt(i)); print(i + 1,(mod%3+(s.charAt(i)-'0')%3)%3,1); }else if(p[i][mod][r] == 1) { print(i+1,mod,r); } } private static class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream file) { reader = new BufferedReader(new InputStreamReader(file)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
9c531593d0ce533b58f87cf01a42e16d
train_001.jsonl
1490625300
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
256 megabytes
/* * Author Ayub Subhaniya * Institute DA-IICT */ import java.io.*; import java.math.*; import java.util.*; public class Driver { InputStream in; PrintWriter out; void solve() { String s=ns(); int n=s.length(); int sum=0; boolean containsZero=false; for (int i=0;i<n;i++) { sum=(sum+s.charAt(i)-'0')%3; if (s.charAt(i)=='0') containsZero=true; } if (sum==0) out.println(s); else { String s1="",s2=""; for (int i=n-1;i>=0;i--) { if ((s.charAt(i)-'0')%3==sum) { s1=s.substring(0,i)+s.substring(i+1); s1=removeTrailingZ(s1); break; } } int flag=-1; for (int i=n-1;i>=0;i--) { if ((s.charAt(i)-'0')%3==0||(s.charAt(i)-'0')%3==sum) continue; if (flag==-1) { flag=i; continue; } s2=s.substring(0,i)+s.substring(i+1,flag)+s.substring(flag+1); s2=removeTrailingZ(s2); break; } if (s1.length()==0&&s2.length()==0) { if (containsZero) out.println(0); else out.println(-1); } else if (s1.length()>s2.length()) out.println(s1); else out.println(s2); } out.close(); } String removeTrailingZ(String s) { String ns=""; for (int i=0;i<s.length();i++) { if (s.charAt(i)!='0') { ns=s.substring(i); break; } } return ns; } void run() throws Exception { String INPUT = "C:/Users/ayubs/Desktop/input.txt"; in = oj ? System.in : new FileInputStream(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Driver().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 = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean inSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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
["1033", "10", "11"]
1 second
["33", "0", "-1"]
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Java 8
standard input
[ "dp", "number theory", "greedy", "math" ]
df9942d1eb66b1f3b5c6b665b446cd3e
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
2,000
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
standard output
PASSED
f2d4c7423919667634a32e9d8c3a450c
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int answer = 0; long min = 0; long max = 0; for (int i = 0; i < n; i++) { int a = scanner.nextInt(); if (a == 0) { if ((min < 0) && (max >= 0)) { min = 0; } else if ((min < 0) && (max < 0)) { answer ++; min = 0; max = m; } else if (min > m){ System.out.print(-1); System.exit(0); } } else { min = min + a; max = max + a; if (min > m) { System.out.print(-1); System.exit(0); } if (max > m) { max = m; } } } System.out.print(answer); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
737928371f2c1be30dcf98d5d184a3bb
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); d893 solver = new d893(); solver.solve(1, in, out); out.close(); } static class d893 { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int d = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } long[] balance = new long[n]; balance[0] = a[0]; for (int i = 1; i < n; i++) { balance[i] = balance[i - 1] + a[i]; } long[] balanceMax = new long[n]; balanceMax[n - 1] = balance[n - 1]; for (int i = n - 2; i >= 0; i--) { balanceMax[i] = Math.max(balance[i], balanceMax[i + 1]); } int ans = 0; long sum = 0; for (int i = 0; i < n; i++) { if (balance[i] + sum > d) { out.println(-1); return; } if (a[i] == 0 && balance[i] + sum < 0) { long maxBal = sum + balanceMax[i]; long add = d - maxBal; if (balance[i] + sum + add < 0) { out.println(-1); return; } sum += add; ans++; } } out.println(ans); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
edf46f04c7d6cd7799a3e58e4b9f0a08
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { InputStream is; PrintWriter out; String INPUT = ""; long MOD = 1_000_000_007; int inf = 10000000; void solve() { int n = ni(); int d = ni(); int[] a = new int[n]; int[] b = new int[n]; for(int i = 0; i < n; i++){ a[i] = ni(); if(i==0) b[i] = a[i]; else b[i] = b[i-1] + a[i]; } for(int i = 0; i < n; i++){ if(b[i]>d){ out.println(-1); return; } } int s = 0; int c = 0; int max = 2000000000; int[] p = new int[n]; int t = 0; long ans = 0; for(int i = n-1; i >= 0; i--){ p[i] = Math.min(d-b[i], max); max = p[i]; } for(int i = 0; i < n; i++){ if(a[i]==0){ int x = b[i]+t; if(x<0){ t = p[i]; x = b[i]+t; ans++; } if(x<0){ out.println(-1); return; } } } out.println(ans); } public static class UnionFind{ int parent[]; int rank[]; public UnionFind(int n){ parent = new int[n]; rank = new int[n]; for(int i = 0;i < n;i++){ parent[i] = i; rank[i] = 0; } } boolean same(int x,int y){ return find(x) == find(y); } public int find(int x){ if(parent[x] == x){ return x; }else{ return parent[x] = find(parent[x]); } } public void union(int x,int y){ x = find(x); y = find(y); if(x != y){ if(rank[x] > rank[y]){ parent[y] = x; }else{ parent[x] = y; if(rank[x] == rank[y]){ rank[y]++; } } } return; } public int count(int n){ int ret = 0; for(int i = 0;i < n;i++){ if(i == find(i)){ ret++; } } return ret; } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b) && b != ' ')){ 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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } static class ArrayUtils { public static void fill(double[][] array, double value) { for (double[] a : array) Arrays.fill(a, value); } public static void fill(double[][][] array, double value) { for (double[][] l : array) fill(l, value); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
4853b7b870d9c7afe7855fdd1f8f24f5
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.*; public class CreditCard { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); long d = Integer.parseInt(st.nextToken()); long[] arr = new long[n]; st = new StringTokenizer(f.readLine()); for(int i = 0; i < n; i++){ arr[i] = Long.parseLong(st.nextToken()); } long balance = 0; int count = 0; long[] balances = new long[n]; long[] rightmax = new long[n]; for(int i = 0; i < n; i++){ balances[i] = balance; balance += arr[i]; if(balance > d){ out.println(-1); out.close(); System.exit(0); } } rightmax[n-1] = Math.min(d, d-arr[n-1]); for(int i = n-2; i >= 0; i--){ rightmax[i] = Math.min(d, rightmax[i+1]-arr[i]); } balance = 0; for(int i = 0; i < n; i++){ balance+=arr[i]; if(balance < 0 && arr[i] == 0){ count++; if(rightmax[i] < 0){ out.println(-1); out.close(); System.exit(0); } balance=rightmax[i]; } } out.println(count); out.close(); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
338bdc85b660c344e0269452ab6855a3
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.*; public class ER33Dsubmission { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int d = scan.nextInt(); int[] arr = new int[n]; int[] sum = new int[n]; ST maxims = new ST(n); for(int i = 0; i < n; i++) arr[i] = scan.nextInt(); sum[0] = arr[0]; if(sum[0] > d){ System.out.println(-1); return; } //System.out.println("sum"); for(int i = 1; i < n; i++){ sum[i] = arr[i]+sum[i-1]; maxims.increment(i, i, sum[i]); //System.out.println(i+" "+sum[i]); if(sum[i] > d){ System.out.println(-1); return; } } //System.out.println("------"); //System.out.println(maxims.maximum(1, n)); int ans = 0; int money = 0; for(int i = 0; i < n; i++){ if(arr[i] == 0){ if(money < 0){ //int add = 0-money; //maxims.increment(i, n, add); //System.out.println("maxims"); int max = maxims.maximum(i, n); if(max > d){ System.out.println(-1); return; } int add = d-max; if(money + add < 0){ System.out.println(-1); return; } maxims.increment(i, n, add); // for(int j = 0; j < n; j++){ // System.out.println(j+" "+maxims.maximum(j, j)); // } money += add; ans++; } } money += arr[i]; money = Math.min(d, money); } System.out.println(ans); } static class ST{ int n; int[] lo, hi, max, delta; public ST(int y){ n = y; lo = new int[4*n+1]; hi = new int[4*n+1]; max = new int[4*n+1]; delta = new int[4*n+1]; init(1, 0, n-1); } public void increment(int a, int b, int val){ increment(1, a, b, val); } public int maximum(int a, int b){ return maximum(1, a, b); } public void init(int i, int a, int b){ lo[i] = a; hi[i] = b; if(a == b) return; int m = (a+b)/2; init(2*i, a, m); init(2*i+1, m+1, b); } void prop(int i){ delta[2*i] += delta[i]; delta[2*i+1] += delta[i]; delta[i] = 0; } void update(int i){ max[i] = Math.max(max[2*i]+delta[2*i], max[2*i+1]+delta[2*i+1]); } void increment(int i, int a, int b, int val){ //Lazy Propagation Incrementation //No cover if(b < lo[i] || hi[i] < a){ return; } //Full cover if(a <= lo[i] && hi[i] <= b){ delta[i] += val; return; } //Partial cover prop(i); increment(2*i, a, b, val); //go to left subtree increment(2*i+1, a, b, val); //go to right subtree update(i); } int maximum(int i, int a, int b){ if(b < lo[i] || hi[i] < a){ return Integer.MIN_VALUE; } if(a <= lo[i] && hi[i] <= b){ return max[i]+delta[i]; } prop(i); int minLeft = maximum(2*i, a, b); int minRight = maximum(2*i+1, a, b); update(i); return Math.max(minLeft, minRight); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
3b84926b4ec906dc1d76490ae44530d3
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static long BFS(int cur, ArrayList<ArrayList<Integer>> con, boolean[] vis, long[] arr){ Queue<Integer> q = new LinkedList<Integer>(); q.add(cur); long MIN = arr[cur]; vis[cur] = true; while (!q.isEmpty()){ int u = q.poll(); MIN = Math.min(MIN, arr[u]); vis[u] = true; ArrayList<Integer> co = con.get(u); for (int v : co){ if (!vis[v]){ q.add(v); } } } return MIN; } public static void main (String[] args) throws java.lang.Exception { // your code goes here MyScanner sc = new MyScanner(); int n = sc.nextInt(); long d = sc.nextLong(); long[] arr = new long[n]; long minPrev = 0L; long maxPrev = 0L; int cnt = 0; for (int i = 0; i < n; ++i){ arr[i] = sc.nextLong(); // System.out.println(i + " minPrev: " + minPrev + " maxPrev: " + maxPrev); if (arr[i] != 0){ minPrev += arr[i]; if (minPrev > d){ System.out.println(-1); return; } maxPrev += arr[i]; if (maxPrev > d) maxPrev = d; }else{ if (maxPrev < 0L){ cnt++; maxPrev = d; minPrev = Math.max(0L, arr[i-1]); } if (minPrev < 0L){ minPrev = 0L; } } } System.out.println(cnt); } public static int GCD(int a, int b){ while (b > 0){ int tmp = b; b = a % b; a = tmp; } return a; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
e20dc5c2ba27364692a8680ce4955d7d
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int n, lazy[], tree[], arr[], pref[]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); n = reader.nextInt(); int d = reader.nextInt(), max_pref_sum = Integer.MIN_VALUE, pref_sum = 0; arr = new int[n]; pref = new int[n]; for(int i=0;i<n;++i) { arr[i] = reader.nextInt(); pref_sum+=arr[i]; pref[i] = pref_sum; max_pref_sum = max(max_pref_sum, pref_sum); } if(max_pref_sum>d) { writer.println(-1); System.exit(0); } int sz = (int)pow(2, ceil(log(n)/log(2))+1); tree = new int[sz]; lazy = new int[sz]; build(1, 0, n-1); int ans = 0; for(int i=0;i<n;++i) { if(arr[i]==0) { //writer.println("i: "+i); if(i>0) { int prev_pref_sum = query(i-1, i-1); //writer.println("Prev pref sum: "+prev_pref_sum); if(prev_pref_sum<0) { if(i<n-1) { int max_that_can_be_added = d-query(i, n-1); //writer.println("max added: "+max_that_can_be_added); if(prev_pref_sum+max_that_can_be_added>=0) { rangeUpdate(i, n-1, max_that_can_be_added); } else { writer.println(-1); System.exit(0); } } ans++; } } } } writer.println(ans); } static void build(int treein, int low, int high) { if(low==high) { tree[treein] = pref[low]; return; } int mid = (low+high)>>1; build(2*treein, low, mid); build(2*treein+1, mid+1, high); tree[treein] = max(tree[2*treein], tree[2*treein+1]); } static void rangeUpdate(int l,int r,int val) { rangeUpdate(1,0,n-1,l,r,val); } static int query(int l,int r) { return query(1,0,n-1,l,r); } static void rangeUpdate(int treein,int low,int high,int l,int r,int val) { if(lazy[treein]!=0) { tree[treein]+=lazy[treein]; if(low!=high) { lazy[2*treein]+=lazy[treein]; lazy[2*treein+1]+=lazy[treein]; } lazy[treein] = 0; } if(l<=low && high<=r) { tree[treein]+=val; if(low!=high) { lazy[2*treein]+=val; lazy[2*treein+1]+=val; } return; } if(low>r || high<l) return; int mid = (low+high)>>1; rangeUpdate(2*treein,low,mid,l,r,val); rangeUpdate(2*treein+1,mid+1,high,l,r,val); tree[treein] = max(tree[2*treein], tree[2*treein+1]); } static int query(int treein,int low,int high,int l,int r) { if(lazy[treein]!=0) { tree[treein]+=lazy[treein]; if(low!=high) { lazy[2*treein]+=lazy[treein]; lazy[2*treein+1]+=lazy[treein]; } lazy[treein] = 0; } if(l<=low && high<=r) return tree[treein]; if(low>r || high<l) return Integer.MIN_VALUE; int mid = (low+high)>>1; return max(query(2*treein+1,mid+1,high,l,r), query(2*treein,low,mid,l,r)); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
d4d171219030cb1c4a0c830167c0fb6e
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class EduD implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { String filename = ""; if (filename.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(filename + ".out"); } } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } <T> ArrayDeque<T>[] createGraphDeque(int size) { ArrayDeque<T>[] list = new ArrayDeque[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayDeque<>(); } return list; } public static void main(String[] args) { new EduD().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int[] log; class Sparse { int[][] data; Sparse(int[] d) { int k = 0; while ((1 << k) < d.length) { k++; } k++; data = new int[k][d.length]; for (int i = 0; i < d.length; i++) { data[0][i] = d[i]; } for (int level = 1; level < k; level++) { for (int start = 0; start < d.length; start++) { int next = start + (1 << (level - 1)); if (next >= d.length) break; data[level][start] = Math.max(data[level - 1][start], data[level - 1][next]); } } } int get(int l, int r) { int k = log[r - l]; int a = data[k][l]; int b = data[k][r - (1 << k) + 1]; return Math.max(a, b); } } List<Integer>[] layersList; int[][] layers; List<Integer>[] g; int[] a; int[] tin; int[] tout; int[] height; int[] indexOnLayer; int timer; void dfs(int v, int p, int h) { tin[v] = timer++; height[v] = h; layersList[h].add(v); indexOnLayer[v] = layersList[h].size() - 1; for (int y : g[v]) { if (y == p) continue; dfs(y, v, h + 1); } tout[v] = timer++; } int findLeftIndex(int v, int k) { int targetH = height[v] + k; if (targetH >= layers.length) return Integer.MAX_VALUE; int l = 0; int r = layers[targetH].length - 1; int ans = Integer.MAX_VALUE; while (l <= r) { int mid = (l + r) >> 1; int vert = layers[targetH][mid]; if (tin[vert] >= tin[v] && tout[vert] <= tout[v]) { //parent ans = mid; r = mid - 1; } else if (tout[vert] < tin[v]) { l = mid + 1; } else { r = mid - 1; } } return ans; } int findRightIndex(int v, int k) { int targetH = height[v] + k; if (targetH >= layers.length) return Integer.MIN_VALUE; int l = 0; int r = layers[targetH].length - 1; int ans = Integer.MIN_VALUE; while (l <= r) { int mid = (l + r) >> 1; int vert = layers[targetH][mid]; if (tin[vert] >= tin[v] && tout[vert] <= tout[v]) { //parent ans = mid; l = mid + 1; } else if (tout[vert] < tin[v]) { l = mid + 1; } else { r = mid - 1; } } return ans; } void solve() throws IOException { int n = readInt(); int d = readInt(); long[] values = new long[n]; int[] a = readIntArray(n); long cur = 0; for (int i = 0; i < n; i++) { cur += a[i]; values[i] = cur; } long[] maxOnSuf = new long[n]; for (int i = n - 1; i >= 0; i--) { maxOnSuf[i] = values[i]; if (i + 1 < n) { maxOnSuf[i] = Math.max(maxOnSuf[i], maxOnSuf[i + 1]); } } int answer = 0; if (maxOnSuf[0] > d) { out.println(-1); return; } long added = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { long now = values[i] + added; if (now < 0) { long todayMaxOnSuf = maxOnSuf[i] + added; long canAdd = d - todayMaxOnSuf; if (now + canAdd < 0) { out.println(-1); return; } answer++; added += canAdd; } } } out.println(answer); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
1e78055c47d4200a8e0e9814457cecb4
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caco */ 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.readInt(); long d = in.readLong(); long[] arr = new long[n]; long[] cumu = new long[n]; long[] max_from_right = new long[n]; for (int i = 0; i < n; i++) { arr[i] = in.readInt(); cumu[i] = (i > 0) ? cumu[i - 1] + arr[i] : arr[i]; if (cumu[i] > d) { out.print(-1); return; } } max_from_right[n - 1] = cumu[n - 1]; for (int i = n - 2; i >= 0; i--) { max_from_right[i] = Math.max(max_from_right[i + 1], cumu[i]); } long cur_added = 0; int ans = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0 && (cumu[i] + cur_added < 0)) { long can_be_added = d - (max_from_right[i] + cur_added); if (can_be_added + cumu[i] + cur_added < 0) { out.print(-1); return; } cur_added += can_be_added; ans++; } } out.print(ans); } } 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 long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 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 print(int i) { writer.print(i); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
d8b3c23815aa441187f58df9d19362dd
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class Ed_2017_R33_D { FastReader in; PrintWriter out; public static void main(String[] args) { new Ed_2017_R33_D().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { int n = in.nextInt(); int d = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int daysAdd = 0, minsum = 0, maxsum = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (minsum < 0) { if (maxsum >= 0) minsum = 0; else { minsum = 0; maxsum = d; daysAdd++; } } } else { minsum += a[i]; maxsum += a[i]; if (minsum > d) { out.println(-1); return; } if (maxsum > d) maxsum = d; } } out.println(daysAdd); } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
97d7dde9a03b91a244e514c060cbd6ce
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.BufferedInputStream; import java.util.Scanner; /** * Created by leen on 23/11/2017. */ public class _893D { public static void main(String[] args) { Scanner scan = new Scanner(new BufferedInputStream(System.in, 1024*64)); int n = scan.nextInt(), d = scan.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = scan.nextInt(); int[] upperBounds = new int[n]; int currentUpperBound = d; for(int i = n-1; i >= 0; i--) { currentUpperBound -= a[i]; currentUpperBound = Math.min(currentUpperBound, d); upperBounds[i] = currentUpperBound; } int current = 0; int ans = 0; for(int i = 0; i < n; i++) { if(current > upperBounds[i]) { System.out.println(-1); return; } if(a[i] == 0) { if(current < 0) { if(upperBounds[i] < 0) { System.out.println(-1); return; } else { current = upperBounds[i]; ans++; } } } else { current += a[i]; } } System.out.println(ans); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
fa2d16a0ffa645770c66a03c42d59674
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Solution { public static void solve(InputReader in, PrintWriter out, DebugWriter debug) throws IOException { int n = in.nextInt(); long d = in.nextInt(); int[] a = in.nextIntArray(n); long[] balance = new long[n]; balance[0] = a[0]; if (balance[0] > d){ out.print(-1); return; } for (int i=1; i<n; i++){ long al = a[i]; balance[i] = balance[i-1]+al; if (balance[i] > d){ out.print(-1); return; } } long[] sufmax = new long[n]; sufmax[n-1] = balance[n-1]; for (int i=n-2; i>=0; i--){ sufmax[i] = Math.max(balance[i], sufmax[i+1]); } long income = 0; long ans = 0; for (int i=0; i<n; i++){ if (a[i] != 0) continue; if (balance[i]+income >= 0) continue; long inc = d-(sufmax[i]+income); income += inc; ans++; if (balance[i]+income < 0){ out.print(-1); return; } } out.print(ans); } public static final String NAME = ""; public static void main(String[] args) throws IOException{ InputReader in; PrintWriter out; DebugWriter debug; if (args.length > 0 && args[0].equals("file")) { in = new InputReader(new BufferedReader(new FileReader("input.txt"))); out = new PrintWriter(new FileWriter("output.txt")); debug = new DebugWriter(true); int sampleNumber = 1; do { String nextSample = "Sample #" + sampleNumber++ + ": "; out.println(nextSample); debug.println(nextSample); solve(in, out, debug); out.println(""); debug.println(""); } while (in.reader.readLine() != null); } else { if (NAME.length() > 0) { in = new InputReader(new BufferedReader(new FileReader(NAME + ".in"))); out = new PrintWriter(new FileWriter(NAME + ".out")); } else { in = new InputReader(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); } debug = new DebugWriter(false); solve(in, out, debug); } in.reader.close(); out.close(); } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(BufferedReader reader) { this.reader = reader; tokenizer = null; } public String next() throws IOException{ while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException{ return Integer.parseInt(next()); } public int[] nextIntArray(int n) throws IOException{ int[] array = new int[n]; for (int i=0; i<n; i++){ array[i] = nextInt(); } return array; } } public static class DebugWriter { public boolean enable; public DebugWriter(boolean enable){ this.enable = enable; } public void print(Object o){ if (enable) System.out.print(o); } public void println(Object o){ if (enable) System.out.println(o); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
f5a117564bc3ad6df499d72ae9e2b101
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
//893D //Credit Card import java.io.*; import java.util.*; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int d = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = sc.nextInt(); long[] maxNxt = new long[n]; maxNxt[n - 1] = arr[n - 1]; for(int i = n - 2; i > -1; i--) maxNxt[i] = Math.max(maxNxt[i + 1] + arr[i], arr[i]); int count = 0; long account = 0; for(int i = 0; i < n; i++) { if(arr[i] == 0) { if(account < 0) { account = Math.max(0, d - maxNxt[i]); count++; } } else { if(account + arr[i] > d) { count = -1; break; } account += arr[i]; } } pw.println(count); pw.flush(); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
bfdd97f78d18d9121488875bf3d56311
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class P893D { public static void main(String[] args) { FastScanner scan = new FastScanner(); int n = scan.nextInt(); int d = scan.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = scan.nextInt(); int dep = 0; int lo = 0, hi = 0; for (int i = 0; i < n; i++) { int p = arr[i]; if (p < 0) { lo += p; hi += p; } else if (p > 0) { lo += p; hi = Math.min(d, hi+p); if (lo > d) { System.out.println(-1); return; } } else { if (hi >= 0) //Don't deposit { lo = Math.max(0, lo); } else //Deposit { dep++; lo = 0; hi = d; } } } System.out.println(dep); } 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 String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
9194c6d82a66ab13551c8e6b7dca793e
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
//package cow17; /* LANG: JAVA TASK: */ import java.io.*; import java.util.*; public class cf4 { public static void main(String[] args) throws IOException { Scanner c = new Scanner(System.in); int N = c.nextInt(), D = c.nextInt(); long[] arr = new long[N]; for(int i=0; i<N; i++) arr[i] = c.nextLong(); long[] pre = new long[N]; pre[0] = arr[0]; if(pre[0] > D) { System.out.println(-1); return; } for(int i=1; i<N; i++) { pre[i] = pre[i-1] + arr[i]; if(pre[i] > D) { System.out.println(-1); return; } } long[] maxPre = new long[N]; maxPre[N-1] = pre[N-1]; for(int i=N-2; i>=0; i--) { maxPre[i] = Math.max(maxPre[i+1], pre[i]); } long curSum = 0; int count = 0; for(int i=0; i<N; i++) { curSum += arr[i]; if(arr[i] == 0 && curSum < 0) { long flood = maxPre[i] - pre[i]; long add = D-(curSum+flood); if(flood > D) { System.out.println(-1); return; } // System.out.println(arr[i-1]); curSum += add; count++; } } System.out.println(count); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
0a04a70ad13f63f84f7b268463f7031c
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
/** * Created by Chirag on 17-12-2017. * DA-IICT (B.tech 3rd year) */ import java.io.*; import java.util.*; public class CreditCard { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String int result = 3*n; out.println(result); // print via PrintWriter */ //The Code Starts here int n,Max=0,Min = 0,x,sol=0,d; n=sc.nextInt(); d=sc.nextInt(); while (n-->0) { x=sc.nextInt(); // debug(Max,Min,x,sol); if(x!=0) { Max+=x; Min+=x; if(Min>d) { System.out.println("-1"); return; } Max=Math.min(Max,d); } else { Min=Math.max(Min,0); if(Max<0) { Max=d; Min=0; sol++; } } // debug(Max,Min,x,sol); // System.out.println(); } System.out.println(sol); //The Code ends here out.close(); } /* int main(){ scanf("%i%i",&n,&d); while(n--){ scanf("%i",&x); if(x){ Max+=x;Min+=x; if(Min>d) return printf("-1"),0; Max=min(Max,d); } else{ Min=max(Min,0); if(Max<0) Max=d,Min=0,sol++; } } printf("%i",sol); return 0; } */ //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char nextCharacter() { return next().charAt(0); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } public static class Pair implements Comparable<Pair> { long u; long v; public Pair(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } //-------------------------------------------------------- // Different other methods public static long pow(long n, long p, long mod) { if (p == 0) return 1; if (p == 1) return n % mod; if (p % 2 == 0) { long temp = pow(n, p / 2, mod); return (temp * temp) % mod; } else { long temp = pow(n, p / 2, mod); temp = (temp * temp) % mod; return (temp * n) % mod; } } public static long pow(long n, long p) { if (p == 0) return 1; if (p == 1) return n; if (p % 2 == 0) { long temp = pow(n, p / 2); return (temp * temp); } else { long temp = pow(n, p / 2); temp = (temp * temp); return (temp * n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } static long modInverse(long a, long m) { long m0 = m, t, q; long x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static class DisjointSet { HashMap<Integer, Node> map = new HashMap<Integer, Node>(); class Node { int data; int rank; Node parent; Node(int data) { this.data = data; this.rank = 0; this.parent = this; } } void makeSet(int data) { map.put(data, new Node(data)); } Node findSet(int data) { return findSet(map.get(data)); } boolean isConnected(int d1, int d2) { return findSet(d1) == findSet(d2); } Node findSet(Node node) { Node parent = node.parent; if (parent == node) return parent; node.parent = findSet(node.parent); return node.parent; } void union(int data1, int data2) { Node d1 = map.get(data1); Node d2 = map.get(data2); Node p1 = findSet(d1); Node p2 = findSet(d2); if (p1.data == p2.data) return; if (p1.rank >= p2.rank) { p1.rank = (p1.rank == p2.rank) ? p1.rank + 1 : p1.rank; p2.parent = p1; } else { p1.parent = p2; } } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
5c5194be0df2773620f804a92587a4f7
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DCreditCard solver = new DCreditCard(); solver.solve(1, in, out); out.close(); } static class DCreditCard { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); long limit = in.scanLong(); long arr[] = new long[n]; in.scanLong(arr); long sum = 0; for (int i = 0; i < n; ++i) { sum += arr[i]; if (arr[i] == 0) { if (sum < 0) sum = 0; } if (sum > limit) { out.println(-1); return; } } sum = 0; int ans = 0; for (int i = 0; i < n; ++i) { sum += arr[i]; if (arr[i] == 0) { if (sum < 0) { ans++; sum = limit; } } if (sum > limit) sum = limit; } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public void scanLong(long[] A) { for (int i = 0; i < A.length; i++) A[i] = scanLong(); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
cf95d5b9ac7d9e4f36c3cc9fe4632678
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import com.sun.org.apache.regexp.internal.RE; import java.io.*; import java.nio.file.ClosedWatchServiceException; import java.security.SecureRandom; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); //String test = "C-large"; //ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + "-out.txt"))); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { int n = io.ri(); int d = io.ri(); int[] line = new int[n]; int prev = 0; boolean[] check = new boolean[n]; for(int i = 0;i<n;i++){ int v = io.ri(); prev+=v; line[i] = prev; if(v == 0)check[i] = true; } int[] max = new int[n]; max[n-1] = line[n-1]; for(int i = n-2;i>=0;i--) { max[i] = Math.max(line[i], max[i + 1]); } int res = 0; int shift = 0; for(int i = 0;i<n;i++){ int v = line[i] + shift; if(v>d){ io.writeLine("-1"); return; } if(check[i] && v<0){ res++; int change = Math.max(d - (max[i]+shift), -v); shift+=change; } } io.writeLine(res+""); } int trav(int cur){ if(visit[cur]) return Integer.MAX_VALUE; int res = gold[cur]; visit[cur] = true; List<Integer> ch = gr.get(cur); for(int i =0;i<ch.size();i++){ int next = ch.get(i); res = Math.min(res, trav(next)); } return res; } int[] gold; boolean[] visit; } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
03d83de38b5c16ab60ff25851be891ff
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverseOrder; import static java.util.Collections.shuffle; import static java.util.Collections.sort; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { int n = in.nextInt(); long d = in.nextLong(); long[] a = new long[n]; ArrayList<Integer> zero = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = in.nextLong(); if (a[i] == 0) zero.add(i); } long[] v = new long[n]; long max = Long.MIN_VALUE; for (int i = 0; i < n; i++) { v[i] = (i > 0 ? v[i - 1] : 0) + a[i]; max = max(max, v[i]); } if (max > d) { out.println(-1); return; } long min = Long.MAX_VALUE; for (int i : zero) min = min(min, v[i]); long ans = 0; if (min < 0) { long[] maxAdd = new long[zero.size()]; for (int i = 0; i < maxAdd.length; i++) { long cur = Long.MAX_VALUE; for (int j = zero.get(i); j < (i + 1 < zero.size() ? zero.get(i + 1) : n); j++) { cur = min(cur, d - v[j]); } maxAdd[i] = cur; } for (int i = maxAdd.length - 2; i >= 0; i--) maxAdd[i] = min(maxAdd[i], maxAdd[i + 1]); long[] need = new long[zero.size()]; for (int i = 0; i < zero.size(); i++) need[i] = max(0, -v[zero.get(i)]); for (int i = 1; i < need.length; i++) { need[i] = max(need[i], need[i - 1]); } boolean ok = true; for (int i = 0; i < zero.size(); i++) { ok &= maxAdd[i] >= need[i]; } if (!ok) { out.println(-1); return; } long add = 0; for (int i = 0; i < zero.size(); i++) { if (need[i] > 0 && add < need[i]) { add = maxAdd[i]; ans++; } } } out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // in = new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
e7f5debf7ce32fe73ba561536ec6b991
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; 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 n; int limit; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); limit = in.nextInt(); long max = 0, balanse = 0, res = 0; for (int i = 0; i < n; ++i) { int x = in.nextInt(); if (x == 0) { if (!check(balanse)) { if (0 - balanse <= max) { max -= (0 - balanse); balanse = 0; } else { ++res; max = limit; balanse = 0; } } } else if (x > 0) { if (balanse + x > limit) { if (max - x < 0) { out.println(-1); return; } max -= x; balanse = max; } else { balanse += x; max = Math.min(max, limit - Math.max(0, balanse)); } } else { balanse += x; } } out.println(res); } private boolean check(long balanse) { return balanse >= 0; } } 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
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
f653356612cde7fd814cacec8d8d5043
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.*; public class ER33Dsubmission { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int d = scan.nextInt(); int[] arr = new int[n]; int[] sum = new int[n]; ST maxims = new ST(n); for(int i = 0; i < n; i++) arr[i] = scan.nextInt(); sum[0] = arr[0]; if(sum[0] > d){ System.out.println(-1); return; } //System.out.println("sum"); for(int i = 1; i < n; i++){ sum[i] = arr[i]+sum[i-1]; maxims.increment(i, i, sum[i]); //System.out.println(i+" "+sum[i]); if(sum[i] > d){ System.out.println(-1); return; } } //System.out.println("------"); //System.out.println(maxims.maximum(1, n)); int ans = 0; int money = 0; for(int i = 0; i < n; i++){ if(arr[i] == 0){ if(money < 0){ //int add = 0-money; //maxims.increment(i, n, add); //System.out.println("maxims"); int max = maxims.maximum(i, n); if(max > d){ System.out.println(-1); return; } int add = d-max; if(money + add < 0){ System.out.println(-1); return; } maxims.increment(i, n, add); // for(int j = 0; j < n; j++){ // System.out.println(j+" "+maxims.maximum(j, j)); // } money += add; ans++; } } money += arr[i]; money = Math.min(d, money); } System.out.println(ans); } static class ST{ int n; int[] lo, hi, max, delta; public ST(int y){ n = y; lo = new int[4*n+1]; hi = new int[4*n+1]; max = new int[4*n+1]; delta = new int[4*n+1]; init(1, 0, n-1); } public void increment(int a, int b, int val){ increment(1, a, b, val); } public int maximum(int a, int b){ return maximum(1, a, b); } public void init(int i, int a, int b){ lo[i] = a; hi[i] = b; if(a == b) return; int m = (a+b)/2; init(2*i, a, m); init(2*i+1, m+1, b); } void prop(int i){ delta[2*i] += delta[i]; delta[2*i+1] += delta[i]; delta[i] = 0; } void update(int i){ max[i] = Math.max(max[2*i]+delta[2*i], max[2*i+1]+delta[2*i+1]); } void increment(int i, int a, int b, int val){ //Lazy Propagation Incrementation //No cover if(b < lo[i] || hi[i] < a){ return; } //Full cover if(a <= lo[i] && hi[i] <= b){ delta[i] += val; return; } //Partial cover prop(i); increment(2*i, a, b, val); //go to left subtree increment(2*i+1, a, b, val); //go to right subtree update(i); } int maximum(int i, int a, int b){ if(b < lo[i] || hi[i] < a){ return Integer.MIN_VALUE; } if(a <= lo[i] && hi[i] <= b){ return max[i]+delta[i]; } prop(i); int minLeft = maximum(2*i, a, b); int minRight = maximum(2*i+1, a, b); update(i); return Math.max(minLeft, minRight); } } } /* 7 10 -5 0 9 -10 0 10 0 */
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
fa0ca5c22cafeb201694cb3af0ea09d7
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
/* * Remember a 7.0 student can know more than a 9.8 student. * Grades don't determine intelligence, they test obedience. * I Never Give Up. */ import java.util.*; import java.io.*; import java.util.Comparator.*; import static java.lang.System.out; import static java.util.Arrays.sort; import static java.lang.Math.pow; //import static java.lang.Math.sqrt; //import static java.lang.Math.ceil; //import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; //import static java.lang.Math.floor; public class ContestMain { private static long MOD=1000000007;//10^9+7 private static final int N=(int)200005; // private static ArrayList<Integer> v[]=new ArrayList[N]; // private static long color[]=new long[2]; //For Graph Coloring // private static boolean mark[]=new boolean [N]; // static int choice=Integer.MAX_VALUE,trav=Integer.MAX_VALUE; // static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // public static void dfs(int node){mark[node]=true;for(int x:v[node]){if(!mark[x]){dfs(x);}}} static Reader in=new Reader(); public static void solve(long ar[],int n,long d){ long maxv=Long.MIN_VALUE,curr=0; int cnt=0; int i=0,ind=0; LinkedList<Integer> ll=new LinkedList(); for(i=0;i<n;i++){ if(ar[i]>maxv)maxv=ar[i]; if(ar[i]==0&&curr<0){ if(ll.isEmpty()){ ll.add(i); curr=0; cnt++; } else if(ar[ll.peek()]+(-curr)<=d&&-curr+maxv<=d){ ar[ll.peek()]+=-curr; curr=0; } else{ ll.addFirst(i); curr=0; maxv=Long.MIN_VALUE; cnt++; } } else{ curr+=ar[i]; if(curr>d)break; } } if(i<n)out.println(-1); else out.println(cnt); } public static void main(String[] args) throws IOException{ int n=in.nextInt(); long d=in.nextLong(); long ar[]=new long[n]; for(int i=0;i<n;i++) ar[i]=in.nextLong(); solve(ar,n,d); } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
91a37379ed4481d8194a6da6b2f56f71
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
/* * Remember a 7.0 student can know more than a 9.8 student. * Grades don't determine intelligence, they test obedience. * I Never Give Up. */ import java.util.*; import java.io.*; import java.util.Comparator.*; import static java.lang.System.out; import static java.util.Arrays.sort; import static java.lang.Math.pow; //import static java.lang.Math.sqrt; //import static java.lang.Math.ceil; //import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; //import static java.lang.Math.floor; public class ContestMain { private static long MOD=1000000007;//10^9+7 private static final int N=(int)200005; // private static ArrayList<Integer> v[]=new ArrayList[N]; // private static long color[]=new long[2]; //For Graph Coloring // private static boolean mark[]=new boolean [N]; // static int choice=Integer.MAX_VALUE,trav=Integer.MAX_VALUE; // static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // public static void dfs(int node){mark[node]=true;for(int x:v[node]){if(!mark[x]){dfs(x);}}} static Reader in=new Reader(); public static void solve(long ar[],int n,long d){ long maxv=Long.MIN_VALUE,curr=0; int cnt=0; int i=0,ind=0; LinkedList<Integer> ll=new LinkedList(); long dept[]=new long[n]; for(i=0;i<n;i++){ if(ar[i]>maxv)maxv=ar[i]; if(ar[i]==0&&curr<0){ if(ll.isEmpty()){ ll.add(i); curr=0; cnt++; } else if(dept[ll.peek()]+(-curr)<=d&&-curr+maxv<=d){ dept[ll.peek()]+=-curr; curr=0; } else{ ll.addFirst(i); curr=0; maxv=Long.MIN_VALUE; cnt++; } } else{ curr+=ar[i]; if(curr>d)break; } } if(i<n)out.println(-1); else out.println(cnt); } public static void main(String[] args) throws IOException{ int n=in.nextInt(); long d=in.nextLong(); long ar[]=new long[n]; for(int i=0;i<n;i++) ar[i]=in.nextLong(); solve(ar,n,d); } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
bff8a12a587e3dc663e743ca44e52154
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.*; public class icpc { public static void main(String[] args) throws IOException { Reader in = new Reader(); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = in.nextInt(); long d = in.nextLong(); long[] A = new long[n]; for (int i=0;i<n;i++) A[i] = in.nextLong(); long[] dp = new long[n]; dp[n - 1] = A[n - 1]; for (int i=n - 2;i>=0;i--) dp[i] = Math.max(A[i], A[i] + dp[i + 1]); long sum = 0L; int count = 0; boolean flag = true; for (int i=0;i<n;i++) { if (A[i] == 0 && sum < 0) { if (sum > d) { flag = false; break; } else { long dep = Math.min(d - sum, d - dp[i] - sum); if (sum + dep >= 0) { if (dep > 0) { count ++; sum += dep; } } else { flag = false; break; } } } else sum += A[i]; if (sum > d) { flag = false; break; } } if (flag) System.out.println(count); else System.out.println(-1); } } class DSU { int[] parent; int[] size; //Pass number of total nodes as parameter to the constructor DSU(int n) { this.parent = new int[n]; this.size = new int[n]; Arrays.fill(parent, -1); } public void makeSet(int v) { parent[v] = v; size[v] = 1; } public int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } public void unionSets(int a, int b) { a = findSet(a); b = findSet(b); if (a != b) { if (size[a] < size[b]) { int temp = a; a = b; b = temp; } parent[b] = a; size[a] += size[b]; } } } class FastFourierTransform { private void fft(double[] a, double[] b, boolean invert) { int count = a.length; for (int i = 1, j = 0; i < count; i++) { int bit = count >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; if (i < j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; temp = b[i]; b[i] = b[j]; b[j] = temp; } } for (int len = 2; len <= count; len <<= 1) { int halfLen = len >> 1; double angle = 2 * Math.PI / len; if (invert) angle = -angle; double wLenA = Math.cos(angle); double wLenB = Math.sin(angle); for (int i = 0; i < count; i += len) { double wA = 1; double wB = 0; for (int j = 0; j < halfLen; j++) { double uA = a[i + j]; double uB = b[i + j]; double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB; double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA; a[i + j] = uA + vA; b[i + j] = uB + vB; a[i + j + halfLen] = uA - vA; b[i + j + halfLen] = uB - vB; double nextWA = wA * wLenA - wB * wLenB; wB = wA * wLenB + wB * wLenA; wA = nextWA; } } } if (invert) { for (int i = 0; i < count; i++) { a[i] /= count; b[i] /= count; } } } public long[] multiply(long[] a, long[] b) { int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2; resultSize = Math.max(resultSize, 1); double[] aReal = new double[resultSize]; double[] aImaginary = new double[resultSize]; double[] bReal = new double[resultSize]; double[] bImaginary = new double[resultSize]; for (int i = 0; i < a.length; i++) aReal[i] = a[i]; for (int i = 0; i < b.length; i++) bReal[i] = b[i]; fft(aReal, aImaginary, false); fft(bReal, bImaginary, false); for (int i = 0; i < resultSize; i++) { double real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i]; aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i]; aReal[i] = real; } fft(aReal, aImaginary, true); long[] result = new long[resultSize]; for (int i = 0; i < resultSize; i++) result[i] = Math.round(aReal[i]); return result; } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Long> primeFactorisation(long n) { ArrayList<Long> f = new ArrayList<>(); for(long x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { //Returns an array with the smallest prime factor for each number and primes marked as 0 int[] sieve = new int[n + 1]; for(int x=2;x * x <= n;x++) { if(sieve[x] != 0) continue; for(int u=x*x;u<=n;u+=x) { if(sieve[u] == 0) { sieve[u] = x; } } } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public int maxOfIntArray(int[] A) { int max = Integer.MIN_VALUE; for (int i=0;i<A.length;i++) max = Math.max(max, A[i]); return max; } public long maxOfLongArray(long[] A) { long max = Long.MIN_VALUE; for (int i=0;i<A.length;i++) max = Math.max(max, A[i]); return max; } public int minOfIntArray(int[] A) { int min = Integer.MAX_VALUE; for (int i=0;i<A.length;i++) min = Math.min(min, A[i]); return min; } public long minOfLongArray(long[] A) { long min = Long.MAX_VALUE; for (int i=0;i<A.length;i++) min = Math.min(min, A[i]); return min; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.x == obj.x && this.y == obj.y) return true; return false; } @Override public int hashCode() { return (int)this.x; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } } class Trie { private class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; public TrieNode() { children = new HashMap<>(); endOfWord = false; } } private final TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { node = new TrieNode(); current.children.put(ch, node); } current = node; } current.endOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { return false; } current = node; } return current.endOfWord; } public void delete(String word) { delete(root, word, 0); } private boolean delete(TrieNode current, String word, int index) { if (index == word.length()) { if (!current.endOfWord) { return false; } current.endOfWord = false; return current.children.size() == 0; } char ch = word.charAt(index); TrieNode node = current.children.get(ch); if (node == null) { return false; } boolean shouldDeleteCurrentNode = delete(node, word, index + 1); if (shouldDeleteCurrentNode) { current.children.remove(ch); return current.children.size() == 0; } return false; } } class SegmentTreeLazy { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int input[]) { int nextPowOfTwo = nextPowerOfTwo(input.length); int segmentTree[] = new int[nextPowOfTwo*2 -1]; for(int i=0; i < segmentTree.length; i++){ segmentTree[i] = Integer.MAX_VALUE; } constructMinSegmentTree(segmentTree, input, 0, input.length - 1, 0); return segmentTree; } private void constructMinSegmentTree(int segmentTree[], int input[], int low, int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/2; constructMinSegmentTree(segmentTree, input, low, mid, 2 * pos + 1); constructMinSegmentTree(segmentTree, input, mid + 1, high, 2 * pos + 2); segmentTree[pos] = Math.min(segmentTree[2*pos+1], segmentTree[2*pos+2]); } public void updateSegmentTreeRangeLazy(int input[], int segmentTree[], int lazy[], int startRange, int endRange, int delta) { updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, 0, input.length - 1, 0); } private void updateSegmentTreeRangeLazy(int segmentTree[], int lazy[], int startRange, int endRange, int delta, int low, int high, int pos) { if(low > high) { return; } if (lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(startRange > high || endRange < low) { return; } if(startRange <= low && endRange >= high) { segmentTree[pos] += delta; if(low != high) { lazy[2*pos + 1] += delta; lazy[2*pos + 2] += delta; } lazy[pos] = 0; } int mid = (low + high)/2; updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, low, mid, 2*pos+1); updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, mid+1, high, 2*pos+2); segmentTree[pos] = Math.min(segmentTree[2*pos + 1], segmentTree[2*pos + 2]); } public int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int len) { return rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, 0, len - 1, 0); } private int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int low, int high, int pos) { if(low > high) { return Integer.MAX_VALUE; } if (lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(qlow > high || qhigh < low) { return Integer.MAX_VALUE; } if(qlow <= low && qhigh >= high) { return segmentTree[pos]; } int mid = (low+high)/2; return Math.min(rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, low, mid, 2 * pos + 1), rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2)); } } class BIT1 { int size; int[] table; public BIT1(int size) { table = new int[size]; this.size = size; } void update(int i, long delta) { while (i > 0) { table[i] += delta; i -= Integer.lowestOneBit(i); } } int sum(int i) { int sum = 0; while (i < size) { sum += table[i]; i += Integer.lowestOneBit(i); } return sum; } } class BIT2 { int size; int[] table; public BIT2(int size) { table = new int[size]; this.size = size; } void update(int i, long delta) { while (i < size) { table[i] += delta; i += Integer.lowestOneBit(i); } } int sum(int i) { int sum = 0; while (i > 0) { sum += table[i]; i -= Integer.lowestOneBit(i); } return sum; } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
e435ef0b1637f8dcea555b4fdda9513d
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.PrintWriter; import java.util.*; /** * Created by trung.pham on 25/12/17. */ public class D_Edu_Round_33 { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int d = in.nextInt(); long[]cur = new long[n]; long[]data = new long[n]; ArrayList<Integer> list = new ArrayList(); for(int i = 0; i < n; i++){ data[i] = in.nextInt(); cur[i] += data[i]; if(i > 0){ cur[i] += cur[i - 1]; } if(data[i] == 0){ list.add(i); } } // System.out.println ( Arrays.toString(cur)); long[]max = new long[n]; for(int i = n - 1; i >= 0; i --){ max[i] = cur[i]; if(i + 1 < n){ max[i] = max(max[i], max[i + 1]); } } // System.out.println(Arrays.toString(max) + " " + Arrays.toString(cur)); int result = max[0] > d ? -1 : 0; long tmp = 0; for(int i = 0; i < list.size() && result != -1; i++){ int index = list.get(i); long v = cur[index]; if(v < 0){ v = -v; if(tmp >= v){ v = 0; }else{ tmp = v; } }else{ v = 0; } if(v == 0){ continue; } // System.out.println(index); if(max[index] + v > d){ result = -1; }else{ long mx = max[index]; result++; int nxt = i + 1; while(nxt < list.size()){ index = list.get(nxt); v = cur[index]; if(v < 0){ v = -v; }else{ v = 0; } // System.out.println(v + " " + mx); if(v == 0 || tmp >= v){ }else{ if(mx + v > d){ break; }else{ tmp = v; } } nxt++; } i = --nxt; } } out.println(result); out.close(); } static long max(long a, long b){ return a < b ? b : a; } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
8ad7e8f0134fad52c5996c6648183d2c
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; public class Main{ public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); long d=in.nextLong(); long a[]=new long [n]; for(int i=0;i<n;i++) { a[i]=in.nextLong(); } long val=0; long want[]=new long[n]; for(int i=0;i<n;i++) { if(a[i]==0) { if(val<0) { want[i]=-1L*val; val=0L; } } else { val+=a[i]; } if(val>d) { pw.println(-1); pw.flush(); pw.close(); System.exit(0); } a[i]=val; } int ans=0; long have=0; for(int i=n-1;i>=0;i--) { have+=want[i]; if(a[i]+have>d) { have=0; ans++; } } if(have>0) ans++; pw.println(ans); pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } /* public static long primeFactorization(long n) { HashSet<Integer> a =new HashSet<Integer>(); long cnt=0; for(int i=2;i*i<=n;i++) { while(a%i==0) { a.add(i); a/=i; } } if(a!=1) cnt++; //a.add(n); return cnt; }*/ public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair>{ Long x; Long y; Integer z; pair(long l,long y2,int z){ this.x=l; this.y=y2; this.z=z; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString(){ return (x+" "+y); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
e9f13b665deb0059563a3f0c2240eb4c
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Stack; public class Tester { InputStream is; PrintWriter out; String INPUT = ""; int[] visited; void solve() { int n = ni(), d = ni(); int[] a = na(n); long low = 0, high = 0; int ans = 0; for(int i = 0;i < n;i++){ if(a[i] == 0){ if(high < 0){ ans++; high = d; low = 0; }else{ low = Math.max(low, 0); } }else{ low += a[i]; high += a[i]; high = Math.min(high, d); if(high < low){ out.println(-1); return; } } } out.println(ans); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Tester().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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
3908c51b745a4a65b73b4a387baa2a4c
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class main { static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int d=in.nextInt(); int low=0; int high=0; int ai=0; int count=0; boolean judge=true; for(int i=0;i<n;i++){ ai=in.nextInt(); if(ai==0){ if(high<0){ high=d; count=count+1; } low=Math.max(0,low); }else{ low=low+ai; high=high+ai; high=Math.min(high,d); if(low>d){ judge=false; i=n; } } } if(!judge){ out.println(-1); }else{ out.println(count); } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(1,in,out); out.close(); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
941676e62105a9053b1781d874a991ff
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.StringTokenizer; public class Edu33D { public static void main(String[] args) { FS scan = new FS(System.in); int N = scan.nextInt(); int D = scan.nextInt(); int[] list = new int[N]; for(int i=0;i<N;i++) { list[i] = scan.nextInt(); } long sum = 0; long surplus = 0; int sol = 0; boolean valid = true; for(int i=0;i<N;i++) { if(list[i]==0) { if(sum < 0) { sum = D; sol ++; surplus = D; }else { surplus = Math.min(surplus, sum); } }else { sum+=list[i]; } if(sum>D && sum - D <= surplus) { surplus-=sum - D; sum -= sum - D; }else if (sum > D ) { valid = false; break; } } System.out.println(valid?sol:-1); } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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());} } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
b2fb6d0d4942baedb8573dbe51764d03
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _893D { } */ public class _893D { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); int d = in.readInteger(); int[] a = new int[n]; long rd = 0; long[] rda = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.readInteger(); rd += a[i]; rda[i] = rd; if (rd > d) { System.out.println("-1"); return; } } long[] maxrda = new long[n]; maxrda[n - 1] = rda[n - 1]; for (int i = n - 2; i >= 0; i--) { maxrda[i] = Math.max(rda[i], maxrda[i + 1]); } rd = 0; int ans = 0; long added = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (rd < 0) { long min = -rd; long max = i == n - 1 ? min : d - (maxrda[i + 1] + added); max = Math.min(max, d + min); if (min > max) { System.out.println("-1"); return; } ans++; added += max; rd += max; } } rd += a[i]; } System.out.println(ans); // end here } public static void main(String[] args) throws FileNotFoundException { (new _893D()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
ea89b6036c9b7c135c411e347014c744
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ static final long MOD = (long)1e9+7; static FastReader in; static int MAX = (int)1e6; static ArrayList<Integer>[] adj; public static void main(String[] args){ in = new FastReader(); int N = ni(); long D = nl(); boolean valid = true; long[] a = new long[N+1],prefix = new long[N+1]; for(int i = 1; i<= N; i++){ a[i] = nl(); prefix[i] = prefix[i-1]+a[i]; if(prefix[i] > D)valid = false; } int count = 0; if(valid){ long amount =0; long minAmount = 0, maxAmount = 0; for(int i = 1; i<= N; i++){ if(a[i] == 0){ if(prefix[i]+amount+minAmount >D){ valid = false; }else if(prefix[i]+amount+maxAmount< 0){ count++; amount += minAmount; minAmount = -(prefix[i]+amount); maxAmount = D-(prefix[i]+amount); }else{ minAmount = Math.max(-(prefix[i]+amount), minAmount); maxAmount = Math.min(maxAmount, D-prefix[i]-amount); } }else if(a[i]> 0){ if(prefix[i]+amount+minAmount>D)valid = false; maxAmount = Math.min(maxAmount, D-prefix[i]-amount); } } } pn((valid)?count:-1); } static long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b); } static void p(Object o){ System.out.print(o); } static void pn(Object o){ System.out.println(o); } static String n(){ return in.next(); } static String nln(){ return in.nextLine(); } static int ni(){ return Integer.parseInt(in.next()); } static int[] ia(int N){ int[] a = new int[N]; for(int i = 0; i<N; i++)a[i] = ni(); return a; } static long[] la(int N){ long[] a = new long[N]; for(int i = 0; i<N; i++)a[i] = nl(); return a; } static long nl(){ return Long.parseLong(in.next()); } static double nd(){ return Double.parseDouble(in.next()); } 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
23f8edfbc5affecb854127682ecd24b6
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ static final long MOD = (long)1e9+7; static FastReader in; static int MAX = (int)1e6; static ArrayList<Integer>[] adj; public static void main(String[] args){ in = new FastReader(); int N = ni(); long D = nl(); boolean valid = true; long[] a = new long[N+1],prefix = new long[N+1]; for(int i = 1; i<= N; i++){ a[i] = nl(); prefix[i] = prefix[i-1]+a[i]; if(prefix[i] > D)valid = false; } int count = 0; if(valid){ long amount =0; long minAmount = 0, maxAmount = 0; for(int i = 1; i<= N; i++){ if(a[i] == 0){ if(prefix[i]+amount+minAmount >D){ valid = false; }else if(prefix[i]+amount+maxAmount< 0){ count++; amount += minAmount; minAmount = -(prefix[i]+amount); maxAmount = D-(prefix[i]+amount); }else{ minAmount = Math.max(-(prefix[i]+amount), minAmount); maxAmount = Math.min(maxAmount, D-prefix[i]-amount); } }else if(a[i]> 0){ if(prefix[i]+amount+minAmount>D)valid = false; maxAmount = Math.min(maxAmount, D-prefix[i]-amount); } } } pn((valid)?count:-1); } static long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b); } static void p(Object o){ System.out.print(o); } static void pn(Object o){ System.out.println(o); } static String n(){ return in.next(); } static String nln(){ return in.nextLine(); } static int ni(){ return Integer.parseInt(in.next()); } static int[] ia(int N){ int[] a = new int[N]; for(int i = 0; i<N; i++)a[i] = ni(); return a; } static long[] la(int N){ long[] a = new long[N]; for(int i = 0; i<N; i++)a[i] = nl(); return a; } static long nl(){ return Long.parseLong(in.next()); } static double nd(){ return Double.parseDouble(in.next()); } 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
06ada39be9527c1033239cecc6f89ac7
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } long querySegTree(int low, int high, int pos, int l, int r) { if(low >= l && high <= r) return segTree[pos]; if(low > r || high < l) return Long.MIN_VALUE; int mid = (low + high) >> 1; long val1 = querySegTree(low, mid, 2 * pos + 1, l, r); long val2 = querySegTree(mid + 1, high, 2 * pos + 2, l, r); return max(val1, val2); } void updateSegTree(int low, int high, int pos, int ind, long val) { if(low > ind || high < ind) return; if(low == high) { segTree[pos] = val; return; } int mid = (low + high) >> 1; updateSegTree(low, mid, 2 * pos + 1, ind, val); updateSegTree(mid + 1, high, 2 * pos + 2, ind, val); segTree[pos] = max(segTree[2 * pos + 1], segTree[2 * pos + 2]); } long segTree[]; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); long d = sc.nextLong(); long a[] = new long[n]; long prefix[] = new long[n]; segTree = new long[4 * n]; for(int i = 0; i < n; ++i) a[i] = sc.nextLong(); prefix[0] = a[0]; for(int i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + a[i]; for(int i = 0; i < n; ++i) updateSegTree(0, n - 1, 0, i, prefix[i]); long bal = 0; int days = 0; for(int i = 0; i < n; ++i) { if(bal > d) { w.print("-1"); w.close(); return; } if(a[i] != 0) bal += a[i]; else { if(bal >= 0) continue; long alr = querySegTree(0, n - 1, 0, i, n - 1) + bal; if(i != 0) alr -= prefix[i - 1]; if(alr > d) { w.print("-1"); w.close(); return; } long poss = d - alr; bal += poss; days++; if(bal < 0) { w.print("-1"); w.close(); return; } } } if(bal > d) { w.print("-1"); w.close(); return; } w.print(days); w.close(); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
78434875fd4520fe9fc2d2f2bbc8f250
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
import java.util.Scanner; /** * D. ΠšΡ€Π΅Π΄ΠΈΡ‚Π½Π°Ρ ΠΊΠ°Ρ€Ρ‚Π° * http://codeforces.com/problemset/problem/893/D */ public class Task1_893D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long days = scanner.nextLong(); long d = scanner.nextLong(); long max = 0; //min balance after check day long min = 0; //max balance after check day long result = 0; for (int i=0; i<days; i++) { long a = scanner.nextLong(); if (a != 0) { min += a; max += a; if (min > d) { result = -1; break; } max = Math.min(max, d); } else { if (max >= 0) { min = Math.max(min, 0); } else { result++; min = 0; max = d; } } } System.out.println(result); } }
Java
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
6343048b30c5051cb965a7b1ff343da1
train_001.jsonl
1511449500
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai &gt; 0, then ai bourles are deposited to Luba's account. If ai &lt; 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
256 megabytes
//package educational.round33; 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(), d = ni(); int[] a = na(n); long low = 0, high = 0; int ans = 0; for(int i = 0;i < n;i++){ if(a[i] == 0){ if(high < 0){ ans++; high = d; low = 0; }else{ low = Math.max(low, 0); } }else{ low += a[i]; high += a[i]; high = Math.min(high, d); if(high < low){ out.println(-1); return; } } } out.println(ans); } 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 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
["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"]
2 seconds
["0", "-1", "2"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
c112321ea5e5603fd0c95c4f01808db1
The first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.
1,900
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
standard output
PASSED
b44e490c9fca5165daa484c28ee8aa1b
train_001.jsonl
1368784800
You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class Solve6 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve6().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(), m = sc.nextInt(); long[] a = new long[n], b = new long[m]; for (int i = 0; i < n; i++) { a[i] = sc.nextLong(); } for (int i = 0; i < m; i++) { b[i] = 1 << sc.nextInt(); } int[] x = getBitsFrequency(a), y = getBitsFrequency(b); int ans = m; for (int i = 0; i <= 30; i++) { for (int j = i, k = 1; j <= 30 && y[i] > 0; j++, k *= 2) { int z = y[i] / k + (y[i] % k == 0 ? 0 : 1); if (x[j] < z) { y[i] -= x[j] * k; x[j] = 0; } else { x[j] -= z; if (y[i] % k != 0) { y[i] -= y[i] / k * k; int temp = (1 << j) - (y[i] * (1 << i)); for (int w = 0; w <= 30; w++) { if ((temp & (1 << w)) != 0) { ++x[w]; } } } y[i] = 0; } } } for (int i = 0; i <= 30; i++) { ans -= y[i]; } pw.println(ans); } //bits starts from 0-index public int[] getBitsFrequency(long[] arr) { final int BITS_NUMBER = 32; int[] freq = new int[BITS_NUMBER]; for (long x : arr) { for (int i = 0; i < BITS_NUMBER; i++) { if ((x & (1L << i)) != 0) { ++freq[i]; } } } return freq; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { } } public String next() { if (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 double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { } return null; } public boolean hasNext() throws IOException { if (st != null && st.hasMoreTokens()) { return true; } String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } } }
Java
["5 3\n8 4 3 2 2\n3 2 2", "10 6\n1 1 1 1 1 1 1 1 1 1\n0 0 0 0 0 0"]
2 seconds
["2", "6"]
NoteIn the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8.In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.
Java 11
standard input
[ "binary search", "bitmasks", "greedy" ]
e95fb7d4309747834b37d4bc3468afb7
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 106). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ 2bi ≀ 109).
1,900
Print a single integer β€” the answer to the problem.
standard output
PASSED
eb455c990bf384a71acf26beb2c8332d
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class C496 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); StringBuilder[] sb = new StringBuilder[n]; for (int i = 0; i < n; i++) { sb[i] = new StringBuilder(in.next()); } final int INF = 1000000; int ans = 0; int min = INF; while (true) { min = INF; for (int i = 0; i < n-1; i++) { int len = sb[i].length(); for (int j = 0; j < len; j++) { if (sb[i].charAt(j) < sb[i+1].charAt(j)) { break; } if (sb[i].charAt(j) > sb[i+1].charAt(j)) { min = Math.min(min, j); break; } } } if (min == INF) break; ans++; for (int i = 0; i < n; i++) { sb[i].deleteCharAt(min); } } System.out.println(ans); } void debug(Object...os) { System.err.println(Arrays.deepToString(os)); } } 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
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
3ee4f3aad8ccb82daace7a82473859c4
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static char[][] array; public static char[] spare; public static int vo=-2; public static boolean sorted(char[][] array, int row) { int flag=0; for(int i=1; i<row; i++) { String s1="",s2=""; for(int u=0; u<array[0].length;u++) { s1+=array[i][u]; s2+=array[i-1][u]; } if(s1.compareTo(s2)<0) { vo=i; flag=1; break; } } if(flag==0) return true; return false; } public static void removecol(int col, int row, int c) { for(int y=0; y<row; y++) { array[y][col]='.'; } /*if(c>2) { char[][] anew = new char[row][c-1]; for(int y=0; y<row; y++) { int kp=0; for(int i=0; i<c; i++) { if(i!=col) { anew[y][kp]=array[y][i]; kp++; } } } array=anew; } else { for(int y=0; y<row; y++) { for(int i=0; i<c; i++) { if(i!=col) spare[y]=array[y][i]; } } }*/ } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] y = in.readLine().split(" "); int n = Integer.parseInt(y[0]); int m = Integer.parseInt(y[1]); array = new char[n][m]; spare = new char[n]; for(int x=0; x<n; x++) { String j = in.readLine(); for(int k=0; k<m; k++) array[x][k]=j.charAt(k); } //Arrays.toString(array); int count=0; int x=1; while(!sorted(array,n)) { if(x==n) x=1; for(int j=0; j<array[0].length; j++) { if(array[x][j]<array[x-1][j]) { count++; if(count==m-1) { //System.out.println("YO"); removecol(j,n,array[0].length); if(!sorted(array,n)) { System.out.println(m); return; } System.out.println(m-1); return; } removecol(j,n,array[0].length); j--; } else if(array[x][j]>array[x-1][j]) break; } x++; } //Arrays.toString(array); System.out.println(count); } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
357759e8f58d63a4910326490ef02df3
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.util.Scanner; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); char[][] table = new char[n][m]; for (int r = 0; r < n; r++) { String line = sc.next(); for (int c = 0; c < m; c++) { table[r][c] = line.charAt(c); } } System.out.println(solve(table)); sc.close(); } static int solve(char[][] table) { int n = table.length; int m = table[0].length; StringBuilder[] rows = IntStream.range(0, n).mapToObj(i -> new StringBuilder()).toArray(StringBuilder[]::new); for (int c = 0; c < m; c++) { for (int r = 0; r < n; r++) { rows[r].append(table[r][c]); } if (!IntStream.range(0, n - 1).allMatch(r -> rows[r].toString().compareTo(rows[r + 1].toString()) <= 0)) { for (int r = 0; r < n; r++) { rows[r].deleteCharAt(rows[r].length() - 1); } } } return m - rows[0].length(); } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
1646e8603cb868667f9b2c82f2b91bc7
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
/** * ******* Created on 7/12/19 8:22 PM******* */ import java.io.*; import java.util.*; public class C469 implements Runnable { private static final int MAX = (int) (1E5 + 5); private static final int MOD = (int) (1E9 + 7); private static final int Inf = (int) (1E9 + 10); private void solve() throws IOException { int n = reader.nextInt(); int m = reader.nextInt(); boolean[] col = new boolean[m]; String[] a = new String[n]; for(int i=0;i<n;i++)a[i] = reader.next(); String last = a[0]; for(int i =1;i<n;i++){ String cur =a[i]; boolean back = false; for(int j =0;j<m;j++){ if(!col[j]) if(last.charAt(j) < cur.charAt(j))break; else if(last.charAt(j) > cur.charAt(j)) { col[j] = true; back = true; } } if(back){ last = a[0]; i=0; }else last = cur; } int res = 0; for(int i=0;i<m;i++)if(col[i])res++; writer.println(res); } public static void main(String[] args) throws IOException { try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { new C469().run(); } } StandardInput reader; PrintWriter writer; @Override public void run() { try { reader = new StandardInput(); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } default double nextDouble() throws IOException { return Double.parseDouble(next()); } default int[] readIntArray() throws IOException { return readIntArray(nextInt()); } default int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } default long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < array.length; i++) { array[i] = nextLong(); } return array; } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
73e743ab8ec2ed37a17978bf7f4b8f50
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(); char[][] t = new char[n][m]; for (int i = 0; i < n; i++) t[i] = in.next().toCharArray(); int cnt = 0; for (int j = 0; j < m; j++) { boolean good = true; for (int i = 1; i < n; i++) { String s1 = String.valueOf(t[i - 1], 0, j + 1); String s2 = String.valueOf(t[i], 0, j + 1); if (s1.compareTo(s2) > 0) good = false; } if (!good) { cnt++; for (int i = 0; i < n; i++) t[i][j] = 'a'; } } out.println(cnt); } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
fef4c7e95c83ad52e33cd4b901f841c7
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class C496 { public static int mod = 1000000007; static FasterScanner in = new FasterScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n=in.nextInt(); int m=in.nextInt(); String[] arr=new String[n+1]; for(int i=1;i<=n;i++) { arr[i]=in.nextLine(); } Set<Integer> set=new HashSet<>(); for(int i=1;i<n;i++) { for(int j=0;j<m;j++) { if(set.contains(j)) continue; if(arr[i].charAt(j)>arr[i+1].charAt(j)) { set.add(j); i=0; break; } else if(arr[i].charAt(j)<arr[i+1].charAt(j)) { break; } else if(arr[i].charAt(j)==arr[i+1].charAt(j)) { continue; } } } out.println(set.size()); out.close(); } /////////////////SEGMENT TREE (BUILD-UPDATE-QUERY)///////////////////////////// /////////////////UPDATE FOLLOWING METHODS AS PER NEED////////////////////////// /* public static void buildsegmenttree(int node,int start,int end) { if(start==end) { // Leaf node will have a single element segmenttree[node]=arr[start]; } else { int mid=start+(end-start)/2; // Recurse on the left child buildsegmenttree(2*node, start, mid); // Recurse on the right child buildsegmenttree(2*node+1, mid+1, end); // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static void updatesegmenttree(int node,int start,int end,int idx,int val) { if(start==end) { //Leaf Node arr[idx]+=val; segmenttree[node]+=val; } else { int mid=start+(end-start)/2; if(start<=idx && idx<=mid) { // If idx is in the left child, recurse on the left child updatesegmenttree(2*node, start, mid, idx, val); } else { // if idx is in the right child, recurse on the right child updatesegmenttree(2*node+1, mid+1, end, idx, val); } // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static long querysegmenttree(int node,int start,int end,int l,int r) { if(r<start || end<l) { // range represented by a node is completely outside the given range return 0; } if(l <= start && end <= r) { // range represented by a node is completely inside the given range return segmenttree[node]; } // range represented by a node is partially inside and partially outside the given range int mid=start+(end-start)/2; long leftchild=querysegmenttree(2*node, start, mid, l, r); long rightchild=querysegmenttree(2*node+1, mid+1, end, l, r); return (leftchild+rightchild); } */ public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
1275e5c74a10bbe04e7f0b83dbfd4d34
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
/* *created by Kraken on 26-04-2020 at 14:01 */ //package com.kraken.cf.practice; import java.util.*; import java.io.*; public class C496 { public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(), m = sc.nextInt(); char[][] mat = new char[n][]; for (int i = 0; i < n; i++) mat[i] = sc.next().toCharArray(); Set<Integer> bad = new HashSet<>(); for (int j = 0; j < m; j++) { boolean fine = true; for (int i = 1; i < n; i++) { if (mat[i][j] < mat[i - 1][j]) { boolean found = false; for (int k = j - 1; k >= 0; k--) { if (bad.contains(k)) continue; if (mat[i][k] > mat[i - 1][k]) { found = true; break; } } if (!found) { fine = false; break; } } } if (!fine) bad.add(j); } System.out.println(bad.size()); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
0e9c68988fd1e4599405a1309b19ca5c
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.Arrays; import java.util.Scanner; /** * * @author team02 */ public class C { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner scan = new Scanner(System.in); rows = scan.nextInt(); columns = scan.nextInt(); arr = new char[rows][columns]; for (int i = 0; i < rows; i++) { String str = scan.next(); for (int j = 0; j < columns; j++) { arr[i][j] = str.charAt(j); } } previous = new int[rows]; //influence = new int[rows]; Arrays.fill(previous, 0); /* for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j]); } System.out.println(""); } */ int count = 0; for (int i = 0; i < arr[0].length; i++) { if (!isCorrect(i)) { count++; } } System.out.println(count); } public static char[][] arr; public static int[] previous; //public static int[] influence; static int rows; static int columns; public static boolean isCorrect(int col) { int [] temp = new int [rows]; for (int i = 0; i < rows; i++) { temp[i] = previous[i]; } for (int i = 0; i < arr.length - 1; i++) { if (previous[i] == 1 || temp[i]==1) { //System.out.println(arr[i][col] + " yay " + arr[i + 1][col]); continue; } if (arr[i][col] > arr[i + 1][col]) { //System.out.println(arr[i][col] + " " + arr[i + 1][col] + " " + col); //System.out.println(previous); return false; } else if (arr[i][col] < arr[i + 1][col]) { temp[i] = 1; } else { temp[i] = 0; } } for (int i = 0; i < rows; i++) { previous[i] = temp[i]; } //previous = temp; return true; } } /* code forc esco defo rces */
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
6ea710ce4af2fd03b56bb652c70b996e
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.*; import java.util.*; public class CF_496_C_REMOVING_COLUMNS { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); HashSet<Integer> set = new HashSet<>(); int n = sc.nextInt(); int m = sc.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = sc.next(); while (true) { int old = set.size(); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { char[] s1 = a[i].toCharArray(); char[] s2 = a[j].toCharArray(); boolean g = false; for (int k = 0; k < m; k++) if (s1[k] > s2[k] && !g) set.add(k); else if (s1[k] < s2[k] && !set.contains(k)) g = true; } if (old == set.size()) break; } System.out.println(set.size()); } static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
340f7929e377204e4763ef9c44dbd240
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Euler { public static int check(char[] a, char[] b) { int n = a.length; int i = 0; while (i < n && a[i] == b[i]) i++; if (i < n) { if (a[i] > b[i]) { return i; } } return -1; } public static void main(String[] args){ FastReader in = new FastReader(); PrintWriter o = new PrintWriter(System.out); //long startTime = System.nanoTime(); int n = in.nextInt(); int m = in.nextInt(); char[][] ch = new char[n][m]; for (int i = 0; i < n; i++) ch[i] = in.nextLine().toCharArray(); int ans = 0; while (true) { int f = 0; for (int i = 0; i < n - 1; i++) { int x = check(ch[i], ch[i + 1]); if (x == -1) continue; for (int j = 0; j < n; j++) { ch[j][x] = ' '; } ans++; f = 1; break; } if (f == 0) break; } System.out.println(ans); return; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
7c445bd607d6daceafe97b0b34ce04c2
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.File; import java.util.Scanner; import java.util.StringTokenizer; public class p034 { public static void main(String args[]) throws Exception { // StringTokenizer stok = new StringTokenizer(new Scanner(new File("C:/Users/Arunkumar/Downloads/input.txt")).useDelimiter("\\A").next()); StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(stok.nextToken()); int m = Integer.parseInt(stok.nextToken()); StringBuilder[] s = new StringBuilder[n]; for(int i=0;i<n;i++) s[i] = new StringBuilder(stok.nextToken()); int i=0; int j,cnt=i;; if(i<m) { for(j=i;j<m;j++) { boolean fl=true; for(int k=0;k<n-1 &&fl;k++) if(s[k].substring(i, j+1) .compareTo(s[k+1].substring(i, j+1).toString())>0) fl=false; if(!fl) { for(int k=0;k<n;k++) { s[k].setCharAt(j,'a'); } cnt++; } } } System.out.println(cnt); } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
ff3bb90737abdfdbb84cd0ba12f8ff19
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class RemovingColumns { static int n; static int m; static boolean[] rm; static char[][] arr; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); arr = new char[n][m]; for (int i = 0; i < arr.length; i++) arr[i] = sc.next().toCharArray(); int cnt = 0; for (int i = 0; i < m; i++) { if(valid()) break; if(!valid(i)) { for (int j = 0; j < n; j++) { arr[j][i] = 'a'; } cnt++; } } System.out.println(cnt); } public static boolean valid() { for (int i = 0; i < n-1; i++) { if(string(arr[i]).compareTo(string(arr[i+1])) > 0) return false; } return true; } public static boolean valid(int col) { for (int i = 0; i < n-1; i++) { if(string(arr[i], col).compareTo(string(arr[i+1], col))> 0) return false; } return true; } public static String string(char[] word) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i < word.length; i++) { sb.append("" + word[i]); } return sb.toString(); } public static String string(char[] word, int end) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i <= end; i++) { sb.append("" + word[i]); } return sb.toString(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
4789f7af74bcdfa0cd5ef6174abd8fd3
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.BitSet; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { InputReader in = new InputReader(System.in); int n = in.nextInt(), m = in.nextInt(); int min = 0; boolean[] off = new boolean[m]; String[] rows = new String[n]; for(int i = 0; i < n; i++) rows[i] = in.next(); String last = rows[0]; for(int k = 1; k < n; k++) { String cur = rows[k]; boolean back = false; for(int i = 0; i < m; i++) if(!off[i]) if(cur.charAt(i) > last.charAt(i)) break; else if(cur.charAt(i) < last.charAt(i)) { off[i] = true; back = true; min++; } if(back) { last = rows[0]; k = 0; } else last = cur; } System.out.println(min); } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(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 String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
d9ffda80e93701871d4046c079934358
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nasko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int R = in.nextInt(); int C = in.nextInt(); String[] g = new String[R]; for (int i = 0; i < R; ++i) g[i] = in.nextLine(); if (R == 1) { out.println(0); return; } boolean[] isRemoved = new boolean[C]; for (int iter = 0; iter < 100; ++iter) { for (int j = 0; j < C; ++j) { if (isRemoved[j]) continue; boolean can = true; for (int i = 0; i < R - 1; ++i) { if (g[i].charAt(j) < g[i + 1].charAt(j)) continue; else if (g[i].charAt(j) > g[i + 1].charAt(j)) { boolean isFound = false; for (int m = 0; m < j; ++m) { if (isRemoved[m]) continue; if (g[i].charAt(m) < g[i + 1].charAt(m)) { isFound = true; break; } } if (!isFound) { isRemoved[j] = true; can = false; break; } } } if (!can) break; } } int ret = 0; for (boolean b : isRemoved) if (b) ++ret; out.println(ret); } } 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 String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
fc56c19070b8d4413feb246ecce8fe9e
train_001.jsonl
1418833800
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * * @author Saju * */ public class Main { private static int dx[] = { 1, 0, -1, 0 }; private static int dy[] = { 0, -1, 0, 1 }; private static final long INF = Long.MAX_VALUE; private static final int INT_INF = Integer.MAX_VALUE; private static final long NEG_INF = Long.MIN_VALUE; private static final int NEG_INT_INF = Integer.MIN_VALUE; private static final double EPSILON = 1e-10; private static final int MAX = 10000007; private static final long MOD = 1000000007; private static final int MAXN = 100007; private static final int MAXA = 10000009; private static final int MAXLOG = 22; public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new FileInputStream("src/test.in")); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out"))); /* */ int n = in.nextInt(); int m = in.nextInt(); StringBuilder[] sbs = new StringBuilder[n]; for(int i = 0; i < n; i++) { String s = in.next(); sbs[i] = new StringBuilder(s); } int cnt = 0; for(int j = 0; j < m; j++) { if(!sorted(j, n, sbs)) { if(!isOk(j, n, m, sbs)) { cnt++; for(int i = 0; i < n; i++) { sbs[i].setCharAt(j, '*'); } // System.out.println(j); } } } out.println(cnt); // for(int i = 0; i < n; i++) { // System.out.println(sbs[i]); // } in.close(); out.flush(); out.close(); System.exit(0); } private static boolean sorted(int j, int n, StringBuilder[] strs) { String newS[] = new String[n]; for(int i = 0; i < n; i++) { newS[i] = new String(strs[i].substring(0, j + 1).toString()); } Arrays.sort(newS); for(int i = 0; i < n; i++) { if(!newS[i].equals(strs[i].substring(0, j + 1).toString())) { return false; } } return true; } private static boolean isOk(int j, int n, int m, StringBuilder[] strs) { char ch[] = new char[n]; for(int i = 0; i < n; i++) { ch[i] = strs[i].charAt(j); } Arrays.sort(ch); for(int i = 0; i < n; i++) { if(ch[i] != strs[i].charAt(j)) { return false; } } return true; } private static boolean isPalindrome(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); String str1 = sb.reverse().toString(); return str.equals(str1); } private static String getBinaryStr(int n, int j) { String str = Integer.toBinaryString(n); int k = str.length(); for (int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } private static String getBinaryStr(long n, int j) { String str = Long.toBinaryString(n); int k = str.length(); for (int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } private static long bigMod(long n, long k, long m) { long ans = 1; while (k > 0) { if ((k & 1) == 1) { ans = (ans * n) % m; } n = (n * n) % m; k >>= 1; } return ans; } private static long ceil(long n, long x) { long div = n / x; if(div * x != n) { div++; } return div; } private static int ceil(int n, int x) { int div = n / x; if(div * x != n) { div++; } return div; } private static int abs(int x) { if (x < 0) { return -x; } return x; } private static long abs(long x) { if(x < 0) { return -x; } return x; } private static int lcm(int a, int b) { return (a * b) / gcd(a, b); } private static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private static int log(long x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static long min(long a, long b) { if (a < b) { return a; } return b; } private static int min(int a, int b) { if (a < b) { return a; } return b; } private static long max(long a, long b) { if (a < b) { return b; } return a; } private static int max(int a, int b) { if (a < b) { return b; } return a; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { return null; } return tokenizer.nextToken(); } public String nextLine() { String line = null; try { tokenizer = null; line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public boolean hasNext() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public int[] nextIntArr(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[] nextIntArr1(int n) { int arr[] = new int[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr1(int n) { long arr[] = new long[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextLong(); } return arr; } public void close() { try { if(reader != null) { reader.close(); } } catch(Exception e) { } } } }
Java
["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"]
2 seconds
["0", "2", "4"]
NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Java 8
standard input
[ "constructive algorithms", "implementation", "brute force" ]
a45cfc2855f82f162133930d9834a9f0
The first line contains two integers Β β€” n and m (1 ≀ n, m ≀ 100). Next n lines contain m small English letters eachΒ β€” the characters of the table.
1,500
Print a single numberΒ β€” the minimum number of columns that you need to remove in order to make the table good.
standard output
PASSED
6172c5e6d852a3f82784c00d6d9d45bd
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine().trim()); for(int u=0;u<t;u++) { String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int m=Integer.parseInt(s1[1]); char c[][]=new char[n][m]; for(int i=0;i<n;i++) c[i]=br.readLine().toCharArray(); boolean b=true; int minX[]=new int[26]; int minY[]=new int[26]; int maxX[]=new int[26]; int maxY[]=new int[26]; Arrays.fill(minX,Integer.MAX_VALUE); Arrays.fill(minY,Integer.MAX_VALUE); Arrays.fill(maxX,Integer.MIN_VALUE); Arrays.fill(maxY,Integer.MIN_VALUE); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(c[i][j]=='.') continue; int r=c[i][j]-'a'; minX[r]=Math.min(minX[r],i); maxX[r]=Math.max(maxX[r],i); minY[r]=Math.min(minY[r],j); maxY[r]=Math.max(maxY[r],j); } } for(int i=25;i>=0;i--) { if(minX[i]==Integer.MAX_VALUE) continue; if(minX[i]!=maxX[i] && minY[i]!=maxY[i]) { b=false; break;} if(minX[i]==maxX[i]) { int l=minY[i]; int r=maxY[i]; for(int j=l;j<=r;j++) if(c[minX[i]][j]<i+97) { b=false; break;} } if(minY[i]==maxY[i]) { int l=minX[i]; int r=maxX[i]; for(int j=l;j<=r;j++) if(c[j][minY[i]]<i+97) { b=false; break;} } } int cnt=0; for(int i=24;i>=0;i--) { if(minX[i]==Integer.MAX_VALUE) { minX[i]=minX[i+1]; maxX[i]=maxX[i+1]; minY[i]=minY[i+1]; maxY[i]=maxY[i+1]; } } for(int i=0;i<26;i++) if(minX[i]!=Integer.MAX_VALUE) { cnt++; minX[i]++; maxX[i]++; minY[i]++; maxY[i]++; } if(!b) System.out.println("NO"); else { System.out.println("YES"); System.out.println(cnt); StringBuffer sb=new StringBuffer(); for(int i=0;i<cnt;i++) { sb.append(minX[i]).append(" "); sb.append(minY[i]).append(" "); sb.append(maxX[i]).append(" "); sb.append(maxY[i]); if(i!=cnt-1) sb.append("\n"); } System.out.println(sb); } } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
b692facfffb3320b551f45cf54f79555
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine().trim()); StringBuffer sb=new StringBuffer(); for(int u=0;u<t;u++) { String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int m=Integer.parseInt(s1[1]); char c[][]=new char[n][m]; for(int i=0;i<n;i++) c[i]=br.readLine().toCharArray(); boolean b=true; int minX[]=new int[26]; int minY[]=new int[26]; int maxX[]=new int[26]; int maxY[]=new int[26]; Arrays.fill(minX,Integer.MAX_VALUE); Arrays.fill(minY,Integer.MAX_VALUE); Arrays.fill(maxX,Integer.MIN_VALUE); Arrays.fill(maxY,Integer.MIN_VALUE); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(c[i][j]=='.') continue; int r=c[i][j]-'a'; minX[r]=Math.min(minX[r],i); maxX[r]=Math.max(maxX[r],i); minY[r]=Math.min(minY[r],j); maxY[r]=Math.max(maxY[r],j); } } for(int i=25;i>=0;i--) { if(minX[i]==Integer.MAX_VALUE) continue; if(minX[i]!=maxX[i] && minY[i]!=maxY[i]) { b=false; break;} if(minX[i]==maxX[i]) { int l=minY[i]; int r=maxY[i]; for(int j=l;j<=r;j++) if(c[minX[i]][j]<i+97) { b=false; break;} } if(minY[i]==maxY[i]) { int l=minX[i]; int r=maxX[i]; for(int j=l;j<=r;j++) if(c[j][minY[i]]<i+97) { b=false; break;} } } int cnt=0; for(int i=24;i>=0;i--) { if(minX[i]==Integer.MAX_VALUE) { minX[i]=minX[i+1]; maxX[i]=maxX[i+1]; minY[i]=minY[i+1]; maxY[i]=maxY[i+1]; } } for(int i=0;i<26;i++) if(minX[i]!=Integer.MAX_VALUE) { cnt++; minX[i]++; maxX[i]++; minY[i]++; maxY[i]++; } if(!b) sb.append("NO"); else { sb.append("YES").append("\n"); sb.append(cnt).append("\n"); for(int i=0;i<cnt;i++) { sb.append(minX[i]).append(" "); sb.append(minY[i]).append(" "); sb.append(maxX[i]).append(" "); sb.append(maxY[i]); if(i!=cnt-1) sb.append("\n"); } } if(u!=t-1 && cnt!=0) sb.append("\n"); } System.out.println(sb); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
4fdf7659125ed08fea0a2214dcc28bbb
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), m = in.nextInt(); int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { char[] s = in.next().toCharArray(); for (int j = 0; j < m; j++) map[i][j] = s[j] == '.' ? -1 : s[j] - 'a'; } int inf = (int) 1e9; int[] maxI = new int[26], minI = new int[26], maxJ = new int[26], minJ = new int[26]; fill(maxI, -inf); fill(maxJ, -inf); fill(minI, inf); fill(minJ, inf); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] != -1) { maxI[map[i][j]] = max(maxI[map[i][j]], i); maxJ[map[i][j]] = max(maxJ[map[i][j]], j); minI[map[i][j]] = min(minI[map[i][j]], i); minJ[map[i][j]] = min(minJ[map[i][j]], j); } } } int k = 26; while (k > 0 && maxI[k - 1] < minI[k - 1]) k--; for (int i = 0; i < k; i++) { if (maxI[i] > minI[i] && maxJ[i] > minJ[i]) { out.println("NO"); return; } } for (int i = k - 2; i >= 0; i--) { if (maxI[i] < minI[i]) { maxI[i] = maxI[i + 1]; maxJ[i] = maxJ[i + 1]; minI[i] = minI[i + 1]; minJ[i] = minJ[i + 1]; } } int[][] paint = new int[n][m]; for (int i = 0; i < n; i++) fill(paint[i], -1); for (int c = 0; c < k; c++) for (int i = minI[c]; i <= maxI[c]; i++) for (int j = minJ[c]; j <= maxJ[c]; j++) paint[i][j] = c; boolean ok = true; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ok &= paint[i][j] == map[i][j]; out.println(ok ? "YES" : "NO"); if (ok) { out.println(k); for (int i = 0; i < k; i++) out.println((minI[i] + 1) + " " + (minJ[i] + 1) + " " + (maxI[i] + 1) + " " + (maxJ[i] + 1)); } } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); for (int t = in.nextInt(); t-- > 0; ) solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
f7ed13a1963f444b994dedc1bfd0887b
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), m = in.nextInt(); int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { char[] s = in.next().toCharArray(); for (int j = 0; j < m; j++) map[i][j] = s[j] == '.' ? -1 : s[j] - 'a'; } int inf = (int) 1e9; int[] maxI = new int[26], minI = new int[26], maxJ = new int[26], minJ = new int[26]; fill(maxI, -inf); fill(maxJ, -inf); fill(minI, inf); fill(minJ, inf); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] != -1) { maxI[map[i][j]] = max(maxI[map[i][j]], i); maxJ[map[i][j]] = max(maxJ[map[i][j]], j); minI[map[i][j]] = min(minI[map[i][j]], i); minJ[map[i][j]] = min(minJ[map[i][j]], j); } } } int k = 26; while (k > 0 && maxI[k - 1] < minI[k - 1]) k--; for (int i = 0; i < k; i++) { if (maxI[i] > minI[i] && maxJ[i] > minJ[i]) { out.println("NO"); return; } } for (int i = k - 2; i >= 0; i--) { if (maxI[i] < minI[i]) { maxI[i] = maxI[i + 1]; maxJ[i] = maxJ[i + 1]; minI[i] = minI[i + 1]; minJ[i] = minJ[i + 1]; } } int[][] paint = new int[n][m]; for (int i = 0; i < n; i++) fill(paint[i], -1); for (int c = 0; c < k; c++) for (int i = minI[c]; i <= maxI[c]; i++) for (int j = minJ[c]; j <= maxJ[c]; j++) paint[i][j] = c; boolean ok = true; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ok &= paint[i][j] == map[i][j]; out.println(ok ? "YES" : "NO"); if (ok) { out.println(k); for (int i = 0; i < k; i++) out.println((minI[i] + 1) + " " + (minJ[i] + 1) + " " + (maxI[i] + 1) + " " + (maxJ[i] + 1)); } } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); for (int t = in.nextInt(); t-- > 0; ) solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
6d33b8092702031a26d99286d5463f7a
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
//package CodeforcesProject; import java.io.*; import java.lang.*; import java.util.*; public class Main extends IO { public static void main(String[] args) throws Exception { StringBuilder word = new StringBuilder(".abcdefghijklmnopqrstuvwxyz"); Map<String, Pair> answer = new TreeMap<>(); Map<String, Integer> language = new HashMap<>(); for (int i = 0; i < 27; i++) { language.put(Character.toString(word.charAt(i)), i); } int quantity = ReadInt(); cycle: for (int count = 0; count < quantity; count++) { answer.clear(); int[] size = ReadArrayInt(" "); String[][] base = new String[size[0]][]; for (int i = 0; i < size[0]; i++) { base[i] = ReadArrayString(""); } for (int i = 0; i < size[0]; i++) { for (int index = 0; index < size[1]; index++) { if (!base[i][index].equals(".")) { Pair result = answer.get(base[i][index]); if (result != null && result.getFirstElement() instanceof Integer) { if ((int) result.getFirstElement() != i && (int) result.getSecondElement() != index) { WriteString("NO", "\n"); continue cycle; } }else if (result != null && result.getFirstElement() instanceof Pair){ if (!(((int) ((Pair) (result.getFirstElement())).getFirstElement() == i && (int) ((Pair) (result.getSecondElement())).getFirstElement() == i) || ((int) ((Pair) (result.getFirstElement())).getSecondElement() == index && (int) ((Pair) (result.getSecondElement())).getSecondElement() == index))) { WriteString("NO", "\n"); continue cycle; } } answer.merge(base[i][index], Pair.createPair(i, index), (a, b) -> { if (a.getSecondElement() instanceof Pair) { return Pair.createPair(a.getFirstElement(), b); } else { return Pair.createPair(a, b); } }); } } } for (Map.Entry<String, Pair> entry : answer.entrySet()) { if (entry.getValue().getFirstElement() instanceof Integer) { continue; } Pair<Pair, Pair> pair = (Pair<Pair, Pair>) entry.getValue(); Pair first = pair.getFirstElement(); Pair second = pair.getSecondElement(); int starty = (int) first.getFirstElement(); int startx = (int) first.getSecondElement(); int stopy = (int) second.getFirstElement(); int stopx = (int) second.getSecondElement(); //if (startx != stopx && starty != stopy) { // WriteString("NO", "\n"); // continue cycle; //} while (startx != stopx || starty != stopy) { if (!entry.getKey().equals(base[starty][startx])) { if (language.get(entry.getKey()) > language.get(base[starty][startx])) { WriteString("NO", "\n"); continue cycle; } } if (starty != stopy) { starty++; continue; } startx++; } } WriteString("YES", "\n"); if (answer.size() == 0) { WriteString("0", "\n"); continue; } WriteInt(language.get(((TreeMap<String, Pair>) answer).lastKey()), "\n"); int pred = 0; int id = 1; int ans = answer.size(); for (int i = 0; i < ans; i++) { Map.Entry<String, Pair> entry = ((TreeMap<String, Pair>) answer).pollFirstEntry(); for (int i1 = id; i1 < 26; i1++) { if (!entry.getKey().equals(Character.toString(word.charAt(i1)))) { pred++; id++; continue; } id++; break; } if (entry.getValue().getFirstElement() instanceof Integer) { for (int coun = 0; coun < pred + 1; coun++) { WriteArray(new int[]{(int) entry.getValue().getFirstElement() + 1, (int) entry.getValue().getSecondElement() + 1, (int) entry.getValue().getFirstElement() + 1, (int) entry.getValue().getSecondElement() + 1}, " ", "\n"); } pred = 0; continue; } Pair<Pair, Pair> pair = (Pair<Pair, Pair>) entry.getValue(); Pair first = pair.getFirstElement(); Pair second = pair.getSecondElement(); for (int coun = 0; coun < pred + 1; coun++) { WriteArray(new int[]{(int) first.getFirstElement() + 1, (int) first.getSecondElement() + 1, (int) second.getFirstElement() + 1, (int) second.getSecondElement() + 1}, " ", "\n"); } pred = 0; } } print(); } } class math { protected static int gcd(int a, int b) { // NOD if (b == 0) { return a; } return gcd(b, a % b); } protected static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static float gcd(float a, float b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double gcd(double a, double b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double lcm(double a, double b) { // NOK return a / gcd(a, b) * b; } protected static float lcm(float a, float b) { // NOK return a / gcd(a, b) * b; } protected static int lcm(int a, int b) { // NOK return a / gcd(a, b) * b; } protected static long lcm(long a, long b) { return a / gcd(a, b) * b; } } class Division<T extends Number> extends Pair { private Division(T dividend, T divider) { super(dividend, divider); reduce(); } protected static <K extends Number> Division<K> createDivision(K dividend, K divider) { return new Division<>(dividend, divider); } protected void reduce() { if (getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); int gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); long gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); float gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); double gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } } protected void addWithoutReturn(Division number) throws UnsupportedOperationException { add(number, 0); } private Division add(Division number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); Integer Dividend1 = (Integer) number.getFirstElement(); Integer Divider1 = (Integer) number.getSecondElement(); Integer lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Division result = Division.createDivision((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); Long Dividend1 = (Long) number.getFirstElement(); Long Divider1 = (Long) number.getSecondElement(); Long lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Division result = Division.createDivision((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); Float Dividend1 = (Float) number.getFirstElement(); Float Divider1 = (Float) number.getSecondElement(); Float lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Division result = Division.createDivision((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); Double Dividend1 = (Double) number.getFirstElement(); Double Divider1 = (Double) number.getSecondElement(); Double lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Division result = Division.createDivision((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else { throw new UnsupportedOperationException(); } } protected Division addWithReturn(Division number) { return add(number, 1); } protected void multiplyWithoutReturn(Division number) throws UnsupportedOperationException { multiply(number, 0); } protected Division multiplyWithReturn(Division number) throws UnsupportedOperationException { return multiply(number, 1); } private Division multiply(Division number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer first = (Integer) getFirstElement() * (Integer) number.getFirstElement(); Integer second = (Integer) getSecondElement() * (Integer) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Division answer = Division.createDivision(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long first = (Long) getFirstElement() * (Long) number.getFirstElement(); Long second = (Long) getSecondElement() * (Long) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Division answer = Division.createDivision(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float first = (Float) getFirstElement() * (Float) number.getFirstElement(); Float second = (Float) getSecondElement() * (Float) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Division answer = Division.createDivision(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double first = (Double) getFirstElement() * (Double) number.getFirstElement(); Double second = (Double) getSecondElement() * (Double) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Division answer = Division.createDivision(first, second); answer.reduce(); return answer; } else { throw new UnsupportedOperationException(); } } } class Pair<T, T1> { private T first; private T1 second; Pair(T obj, T1 obj1) { first = obj; second = obj1; } protected static <K, V> Pair<K, V> createPair(K element, V element1) { return new Pair<>(element, element1); } protected T getFirstElement() { return first; } protected T1 getSecondElement() { return second; } protected void setFirst(T element) { first = element; } protected void setSecond(T1 element) { second = element; } } class Graph { private int[][] base; private boolean[] used; protected int quantity; private Integer[] pred; private void start(int length) { used = new boolean[length]; pred = new Integer[length]; pred[0] = -1; quantity = 0; } protected void RibMatrixToDefault(int length, int quantity) throws Exception { base = new int[length][]; List<ArrayList<Integer>> inputBase = new ArrayList<>(); for (int i = 0; i < length; i++) { inputBase.add(new ArrayList<>()); } Array x = (int[] input) -> { inputBase.get(input[0] - 1).add(input[1] - 1); inputBase.get(input[0] - 1).add(1); inputBase.get(input[1] - 1).add(input[0] - 1); inputBase.get(input[1] - 1).add(1); }; for (int i = 0; i < quantity; i++) { x.useArray(IO.ReadArrayInt(" ")); } for (int i = 0; i < length; i++) { base[i] = inputBase.get(i).parallelStream().mapToInt(Integer::intValue).toArray(); } start(length); } protected void AdjacencyMatrixToDefault(int length, int dont) throws Exception { base = new int[length][]; List<Integer> buffer = new ArrayList<>(); int[] InputArray; for (int i = 0; i < length; i++) { InputArray = IO.ReadArrayInt(" "); for (int index = 0; index < length; index++) { if (i != index && InputArray[index] != dont) { buffer.add(index); buffer.add(InputArray[index]); } } base[i] = buffer.stream().mapToInt(element -> element).toArray(); buffer.clear(); } start(length); } protected void dfs(int position) throws Exception { used[position] = true; quantity++; int next; for (int index = 0; index < base[position].length; index += 2) { next = base[position][index]; if (!used[next]) { pred[next] = position; dfs(next); } else { if (next != pred[position]) { // if cycle throw new Exception(); } } } } protected int dijkstra(int start, int stop, int size) { start--; stop--; int[] dist = new int[size]; for (int i = 0; i < size; i++) { if (i != start) { dist[i] = Integer.MAX_VALUE; } pred[i] = start; } Queue<int[]> queue = new PriorityQueue<>((int[] first, int[] second) -> Integer.compare(first[1], second[1])); queue.add(new int[]{start, 0}); int position; int[] GetQueue; while (queue.size() != 0) { GetQueue = queue.poll(); position = GetQueue[0]; if (GetQueue[1] > dist[position]) { continue; } for (int index = 0; index < base[position].length; index += 2) { if (dist[position] + base[position][index + 1] < dist[base[position][index]] && !used[base[position][index]]) { dist[base[position][index]] = dist[position] + base[position][index + 1]; pred[base[position][index]] = position; queue.add(new int[]{base[position][index], dist[base[position][index]]}); } } used[position] = true; } return dist[stop] == Integer.MAX_VALUE ? -1 : dist[stop]; } protected boolean FloydWarshall(int[][] base, int length, int dont) { for (int k = 0; k < length; k++) { for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (base[i][k] == dont || base[k][j] == dont) { continue; } int total = base[i][k] + base[k][j]; if (base[i][j] != dont) { base[i][j] = Math.min(base[i][j], total); } else { base[i][j] = total; } } } } for (int index = 0; index < length; index++) { if (base[index][index] != 0) { // if cycle return false; } } return true; } } interface Array { void useArray(int[] a); } interface Method { void use(); } class FastSort { protected static void SortWithoutReturn(int[] array, int length, int ShellHeapMergeMyInsertionSort) { sort(array, ShellHeapMergeMyInsertionSort, length); } protected static int[] SortWithReturn(int[] array, int length, int ShellHeapMergeMyInsertionSort) { int[] base = array.clone(); sort(base, ShellHeapMergeMyInsertionSort, length); return base; } private static void sort(int[] array, int ShellHeapMergeMyInsertionSort, int length) { if (ShellHeapMergeMyInsertionSort < 0 || ShellHeapMergeMyInsertionSort > 4) { Random random = new Random(); ShellHeapMergeMyInsertionSort = random.nextInt(4); } if (ShellHeapMergeMyInsertionSort == 0) { ShellSort(array); } else if (ShellHeapMergeMyInsertionSort == 1) { HeapSort(array); } else if (ShellHeapMergeMyInsertionSort == 2) { MergeSort(array, 0, length - 1); } else if (ShellHeapMergeMyInsertionSort == 3) { StraightMergeSort(array, length); } else if (ShellHeapMergeMyInsertionSort == 4) { insertionSort(array); } } private static void StraightMergeSort(int[] array, int size) { if (size == 0) { return; } int length = (size / 2) + ((size % 2) == 0 ? 0 : 1); Integer[][] ZeroBuffer = new Integer[length + length % 2][2]; Integer[][] FirstBuffer = new Integer[0][0]; for (int index = 0; index < length; index++) { int ArrayIndex = index * 2; int NextArrayIndex = index * 2 + 1; if (NextArrayIndex < size) { if (array[ArrayIndex] > array[NextArrayIndex]) { ZeroBuffer[index][0] = array[NextArrayIndex]; ZeroBuffer[index][1] = array[ArrayIndex]; } else { ZeroBuffer[index][0] = array[ArrayIndex]; ZeroBuffer[index][1] = array[NextArrayIndex]; } } else { ZeroBuffer[index][0] = array[ArrayIndex]; } } boolean position = false; int pointer0, pointer, pointer1, number = 4, NewPointer, count; Integer[][] NewBuffer; Integer[][] OldBuffer; length = (size / 4) + ((size % 4) == 0 ? 0 : 1); while (true) { pointer0 = 0; count = (number / 2) - 1; if (!position) { FirstBuffer = new Integer[length + length % 2][number]; NewBuffer = FirstBuffer; OldBuffer = ZeroBuffer; } else { ZeroBuffer = new Integer[length + length % 2][number]; NewBuffer = ZeroBuffer; OldBuffer = FirstBuffer; } for (int i = 0; i < length; i++) { pointer = 0; pointer1 = 0; NewPointer = pointer0 + 1; if (length == 1) { for (int g = 0; g < size; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } array[g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { array[g] = OldBuffer[pointer0][pointer]; pointer++; } } return; } for (int g = 0; g < number; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { if (OldBuffer[NewPointer][pointer1] == null) { continue; } NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } } pointer0 += 2; } position = !position; length = length / 2 + length % 2; number *= 2; } } private static void ShellSort(int[] array) { int j; for (int gap = array.length / 2; gap > 0; gap /= 2) { for (int i = gap; i < array.length; i++) { int temp = array[i]; for (j = i; j >= gap && array[j - gap] > temp; j -= gap) { array[j] = array[j - gap]; } array[j] = temp; } } } private static void HeapSort(int[] array) { for (int i = array.length / 2 - 1; i >= 0; i--) shiftDown(array, i, array.length); for (int i = array.length - 1; i > 0; i--) { swap(array, 0, i); shiftDown(array, 0, i); } } private static void shiftDown(int[] array, int i, int n) { int child; int tmp; for (tmp = array[i]; leftChild(i) < n; i = child) { child = leftChild(i); if (child != n - 1 && (array[child] < array[child + 1])) child++; if (tmp < array[child]) array[i] = array[child]; else break; } array[i] = tmp; } private static int leftChild(int i) { return 2 * i + 1; } private static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } private static void MergeSort(int[] array, int low, int high) { if (low < high) { int mid = (low + high) / 2; MergeSort(array, low, mid); MergeSort(array, mid + 1, high); merge(array, low, mid, high); } } private static void merge(int[] array, int low, int mid, int high) { int n = high - low + 1; int[] Temp = new int[n]; int i = low, j = mid + 1; int k = 0; while (i <= mid || j <= high) { if (i > mid) Temp[k++] = array[j++]; else if (j > high) Temp[k++] = array[i++]; else if (array[i] < array[j]) Temp[k++] = array[i++]; else Temp[k++] = array[j++]; } for (j = 0; j < n; j++) array[low + j] = Temp[j]; } private static void insertionSort(int[] elements) { for (int i = 1; i < elements.length; i++) { int key = elements[i]; int j = i - 1; while (j >= 0 && key < elements[j]) { elements[j + 1] = elements[j]; j--; } elements[j + 1] = key; } } } class IO { protected static BufferedReader read; protected static boolean FileInput = false; protected static BufferedWriter write; protected static boolean FileOutput = false; private static void startInput() { try { read = new BufferedReader(FileInput ? new FileReader("input.txt") : new InputStreamReader(System.in)); } catch (Exception error) { } } private static void startOutput() { try { write = new BufferedWriter(FileOutput ? new FileWriter("output.txt") : new OutputStreamWriter(System.out)); } catch (Exception error) { } } protected static int ReadInt() throws Exception { if (read == null) { startInput(); } return Integer.parseInt(read.readLine()); } protected static long ReadLong() throws Exception { if (read == null) { startInput(); } return Long.parseLong(read.readLine()); } protected static String ReadString() throws Exception { if (read == null) { startInput(); } return read.readLine(); } protected static int[] ReadArrayInt(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToInt(Integer::parseInt).toArray(); } protected static long[] ReadArrayLong(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToLong(Long::parseLong).toArray(); } protected static String[] ReadArrayString(String split) throws IOException { if (read == null) { startInput(); } return read.readLine().split(split); } protected static void WriteArray(int[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } protected static void WriteArray(Integer[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } protected static void WriteArray(long[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } protected static void WriteArray(Long[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } public static void WriteArray(String[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(array[index]); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } protected static void WriteArray(boolean[] array, String split, String end) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Boolean.toString(array[index])); if (index + 1 != length) { write.write(split); } } write.write(end); } catch (Exception error) { } } protected static void WriteInt(int number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception error) { } } protected static void WriteInt(Integer number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception error) { } } protected static void WriteLong(long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception error) { } } protected static void WriteLong(Long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception error) { } } protected static void WriteString(String word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception error) { } } protected static void WriteChar(char word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception error) { } } protected static void WriteChar(Character word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception error) { } } protected static void WriteEnter() { if (write == null) { startOutput(); } try { write.newLine(); } catch (Exception e) { } } protected static void print() throws Exception { if (write == null) { return; } write.flush(); read.close(); write.close(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
89fb0306c6b09a10aa5549ded9858277
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.math.*; // **** E. Polycarp and snakes **** public class E { static char [] in = new char [1000000]; public static void main (String [] arg) throws Throwable { int t = nextInt(); StringBuilder b = new StringBuilder(t * 100); for (int ii = 0; ii<t; ++ii) { int n = nextInt(); int m = nextInt(); char [][] g = new char [n][]; for (int i = 0; i<n; ++i) g[i] = next().toCharArray(); Pair [] upleft = new Pair[26]; Pair [] downright = new Pair[26]; int max = -1; for (int i = 0; i<n; ++i) { for (int j = 0; j<m; ++j) { if (g[i][j] == '.') continue; int c = g[i][j] - 'a'; if (upleft[c] == null) upleft[c] = new Pair(i,j,c); downright[c] = new Pair(i,j,c); if (c > max) max = c; } } boolean can = true; for (int i = max; i>=0 && can; --i) { Pair P = upleft[i]; Pair Q = downright[i]; if (P == null) { P = upleft[i+1]; Q = downright[i+1]; upleft[i] = P; downright[i] = Q; } P = new Pair(P.x, P.y, P.L); if (P.x != Q.x && P.y != Q.y) { can = false; break; } int dx = (P.x != Q.x) ? 1 : 0; int dy = (P.y != Q.y) ? 1 : 0; while (P.x != Q.x || P.y != Q.y) { if (g[P.x][P.y] != '*' && g[P.x][P.y] != P.L + 'a') can = false; g[P.x][P.y] = '*'; P.x += dx; P.y += dy; } g[Q.x][Q.y] = '*'; } //System.err.println("Finished scan can = " + can); for (int i = 0; i<n; ++i) for (int j = 0; j<m; ++j) if (g[i][j] != '.' && g[i][j] != '*') can = false; //System.err.println("Finished finalscan can = " + can); if (!can) { b = b.append("NO\n"); } else { b = b.append("YES\n"); b = b.append(max + 1); b = b.append("\n"); for (int i = 0; i<=max; ++i) { Pair P = upleft[i]; Pair Q = downright[i]; b = b.append(P.x+1); b = b.append(' '); b = b.append(P.y+1); b = b.append(' '); b = b.append(Q.x+1); b = b.append(' '); b = b.append(Q.y+1); b = b.append("\n"); } } } System.out.print(b); } /************** HELPER CLASSES ***************/ static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}}; static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}}; static class Pair implements Comparable<Pair> {int x,y,L; public Pair(int xx, int yy, int LL){x=xx;y=yy;L=LL;} public int compareTo(Pair p) {return this.L-p.L;}} /************** FAST IO CODE FOLLOWS *****************/ public static long nextLong() throws Throwable { long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48; int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i; } public static int nextInt() throws Throwable {return (int)nextLong();} public static String next() throws Throwable { int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();} return new String(in, 0,cptr); } /**** LIBRARIES ****/ public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;} public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;} public static int[] sieve(int LIM) { int i,count = 0; boolean [] b = new boolean [LIM]; for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;} int [] primes = new int[count]; for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i; return primes; } public static int[] numPrimeFactors(int LIM) { int i,count = 0; int [] b = new int [LIM]; for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;} return b; } public static StringBuilder stringFromArray(int [] a) { StringBuilder b = new StringBuilder(9*a.length); for (int i = 0; i<a.length; ++i) { if (i != 0) b = b.append(' '); b = b.append(a[i]); } return b; } } /* Full Problem Text: After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n \times m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells. Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26. Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 \times l or l \times 1, where l is snake's length. Note that snakes can't bend. When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell. Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes. */
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
e1811858bec4d4f72b6729eace4f496e
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; public class Main { public static int ran; public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); for(int i = 0; i < n; i++) { test(stdin); } //test(stdin); stdin.close(); } public static void test(Scanner stdin) { int n = stdin.nextInt(); int m = stdin.nextInt(); stdin.nextLine(); int[][] table = new int[n][m]; int[][] col = new int[26][2]; int[][] row = new int[26][2]; int highest = 0; for(int i = 0; i < n; i++) { String s = stdin.nextLine(); for(int u = 0; u < m; u++) { if(s.charAt(u) != '.') { table[i][u] = (int)s.charAt(u) - 96; highest = Math.max(highest, table[i][u]); if(col[table[i][u] - 1][0] == 0 || col[table[i][u] - 1][0] > u + 1) { col[table[i][u] - 1][0] = u + 1; } if(col[table[i][u] - 1][1] == 0 || col[table[i][u] - 1][1] < u + 1) { col[table[i][u] - 1][1] = u + 1; } if(row[table[i][u] - 1][0] == 0 || row[table[i][u] - 1][0] > i + 1) { row[table[i][u] - 1][0] = i + 1; } if(row[table[i][u] - 1][1] == 0 || row[table[i][u] - 1][1] < i + 1) { row[table[i][u] - 1][1] = i + 1; } } } } //System.out.println(highest); for(int i = 0; i < highest; i++) { //System.out.println(row[i][0] + " " + col[i][0] + " " + row[i][1] + " " + col[i][1]); if(!checkSnake(table, i + 1, col[i], row[i])) { System.out.println("NO "); return; } } System.out.println("YES"); System.out.println(highest); for(int i = 0; i < highest; i++) { if(col[i][0] == 0) { System.out.println(row[highest-1][0] + " " + col[highest-1][0] + " " + row[highest-1][1] + " " + col[highest - 1][1]); } else { System.out.println(row[i][0] + " " + col[i][0] + " " + row[i][1] + " " + col[i][1]); } } } public static boolean checkSnake(int[][] table, int snake, int[] col, int[] row) { if(col[0] == 0 ) { return true; } if(col[0] != col[1] && row[0] != row[1]) { //System.out.println("zu breit"); return false; } if(col[0] != col[1]) { for(int i = col[0] - 1; i < col[1]; i++) { if(table[row[0] - 1][i] < snake) { //System.out.println(snake + " falscher eintrag " + i + " " + col[0] + " " + row[0]); return false; } } } else { for(int i = row[0] - 1; i < row[1]; i++) { if(table[i][col[0] - 1] < snake) { //System.out.println("falscher eintrag2"); return false; } } } return true; } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
e465b4e82c5d084ddd47e8e89b39a30b
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { static class Task { int NN = 500005; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; boolean [] vis = new boolean[26]; char [][] a; int [][][]p; boolean ok(char c, int n, int m) { int row= -1, col = -1; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(a[i][j] == c) { if(row == -1 && col == -1) { row = i; col = j; } else if(row != -1 && col != -1) { if(i == row) { col = -1; } else if(j == col) { row = -1; } else { return false; } } else if(row == -1) { if(j != col) return false; } else if(col == -1) { if(i != row) return false; } } } } int cc = c - 'a'; if(row != -1) { int l = -1, r = -1; for(int j=0;j<m;++j) { if(a[row][j] == c) { if(l == -1) l = j; r = j; } } for(int j=l;j<=r;++j) { if(a[row][j] < c) { return false; } } p[cc][0][0] = row; p[cc][0][1] = l; p[cc][1][0] = row; p[cc][1][1] = r; return true; } else if(col != -1) { int l = -1, r = -1; for(int i=0;i<n;++i) { if(a[i][col] == c) { if(l == -1) l = i; r = i; } } for(int i=l;i<=r;++i) { if(a[i][col] < c) { return false; } } p[cc][0][0] = l; p[cc][0][1] = col; p[cc][1][0] = r; p[cc][1][1] = col; return true; } else { return true; } } public void solve(InputReader in, PrintWriter out) { int t= in.nextInt(); while(t-->0) { int n = in.nextInt(); int m = in.nextInt(); a = new char[n][m]; p = new int[26][2][2]; Arrays.fill(vis, false); for(int i=0;i<n;++i) { String str = in.next(); for(int j=0;j<m;++j) { a[i][j] = str.charAt(j); if(a[i][j] != '.') { vis[a[i][j]-'a'] = true; } } } boolean yes = true; for(int i=0;i<26;++i) { if(!ok((char)('a' + i), n, m)) { yes = false; break; } } if(yes) { out.println("YES"); print(n, m, out); } else { out.println("NO"); } } } void print(int n, int m, PrintWriter out) { int last = -1; for(int i=0;i<26;++i) { if(vis[i]) { last = i; } } out.println(last+1); for(int i=0;i<=last;++i) { if(!vis[i]) { p[i][0][0] = p[last][0][0]; p[i][0][1] = p[last][0][1]; p[i][1][0] = p[last][1][0]; p[i][1][1] = p[last][1][1]; } out.println((p[i][0][0]+1) + " " + (p[i][0][1]+1) + " " + (p[i][1][0]+1) + " " + (p[i][1][1]+1)); } } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
9f71bd6d789f305f55519f3d6dcc4736
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Math.*; public class code0 { private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static Reader in; private static PrintWriter out; //////////////////////////////////////////////////////////////////////////////////////////////////// private static int min(int... a){int min=a[0]; for(int i:a) min=Math.min(min, i); return min;} private static int max(int... a){int max=a[0]; for(int i:a) max=Math.max(max, i); return max;} private static long min(long... a){long min=a[0]; for(long i:a)min=Math.min(min, i); return min;} private static long max(long... a){long max=a[0]; for(long i:a)max=Math.max(max, i); return max;} private static String strm(String str, long m) { String ans=""; while(m>0) { if(m%2==1) ans=ans.concat(str); str=str.concat(str); m>>=1; } return ans; } private static long mod(long a, long mod) {long res = a%mod; return res>=0 ? res : res+mod;} private static int mod(int a, int mod) {int res = a%mod; return res>=0 ? res : res+mod;} private static long modpow(long x, int n, int mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = mod((mod(p, mod)*mod(p, mod)), mod)) { if ((n & 1) != 0) res = mod(mod(res, mod) * mod(p, mod), mod); } return res; } private static long gcd(long a, long b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);} private static int gcd(int a, int b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);} private static long gcd(long... a) {long gcd=a[0]; for(long x:a) gcd=gcd(gcd, x); return gcd;} private static int gcd(int... a) {int gcd=a[0]; for(int x:a) gcd=gcd(gcd, x); return gcd;} private static long lcm(long a, long b) {return Math.abs(a / gcd(a, b) * b);} private static boolean isEven(int num) {return ((num&1) == 0);} private static boolean isOdd(int num) {return !isEven(num);} private static boolean isEven(long num) {return ((num&1) == 0);} private static boolean isOdd(long num) {return !isEven(num);} private static class Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Pair)) return false; Pair pair = (Pair)obj; return this.x == pair.x && this.y == pair.y; } @Override public String toString() { return ("(" + this.x + "," + this.y + ")"); } @Override public int hashCode() { return (this.x+" "+this.y).hashCode(); } } private static class Triplet { public int x, y, z; public Triplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Triplet)) return false; Triplet triplet = (Triplet)obj; return this.x == triplet.x && this.y == triplet.y && this.z == triplet.z; } @Override public String toString() { return ("(" + this.x + "," + this.y + "," + this.z + ")"); } @Override public int hashCode() { return (this.x+" "+this.y+" "+this.z).hashCode(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// static class Reader { private BufferedReader br; private StringTokenizer token; private Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } private Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } private String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } private String nextLine() { String str=""; try { str = br.readLine(); } catch (Exception e) {e.printStackTrace();} return str; } private int nextInt() {return Integer.parseInt(next());} private long nextLong() {return Long.parseLong(next());} private double nextDouble() {return Double.parseDouble(next());} private long[] nextLongArr(int n) { long[] arr = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } private int[] nextIntArr(int n) { int[] arr = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } } //////////////////////////////////////////////////////////////////////////////////////////////////// private static final int mod = 1_000_000_007; private static char[][] arr; private static ArrayList<ArrayList<Pair>> al; private static int[] flag; private static void solve() throws Exception { int t = in.nextInt(); nextCase: while (t-- >0) { int n = in.nextInt(), m = in.nextInt(); arr = new char[n][m]; flag = new int[26]; for (int i=0; i<n; i++) arr[i] = in.nextLine().toCharArray(); al = new ArrayList<>(); for (int i=0; i<26; i++) { al.add(new ArrayList<>()); } for (int i=0; i<n; i++) { for (int j=0; j<m; j++) { if (arr[i][j] == '.') continue; int ind = arr[i][j] - 'a'; if (al.get(ind).size() == 0) al.get(ind).add(new Pair(i, j)); else if (al.get(ind).size() == 1) { if (al.get(ind).get(0).x == i) flag[ind] = 1; else if (al.get(ind).get(0).y == j) flag[ind] = 2; else {out.printf("%s\n", "NO"); continue nextCase;} al.get(ind).add(new Pair(i, j)); } else { if ((al.get(ind).get(al.get(ind).size()-1).x == i) && (flag[ind] == 1)) al.get(ind).add(new Pair(i, j)); else if ((al.get(ind).get(al.get(ind).size()-1).y == j) && (flag[ind] == 2)) al.get(ind).add(new Pair(i, j)); else {out.printf("%s\n", "NO"); continue nextCase;} } } } // for (int i=0; i<26; i++) out.println(al.get(i).toString()); int lastAlpha = 25; loop: for (int i=25; i>=0; i--) { if (al.get(i).size() == 0) { lastAlpha--; } if (al.get(i).size() != 0) {break loop;} } char[][] newarr = new char[n][m]; for (int i=0; i<n; i++) Arrays.fill(newarr[i], '.'); for (int i=0; i<26; i++) { char ch = (char)(i+97); if (al.get(i).size() == 0) continue; Pair start = al.get(i).get(0), end = al.get(i).get(al.get(i).size()-1); if (flag[i] == 1) { for (int j = start.y; j<=end.y; j++) newarr[start.x][j] = ch; } else { for (int j = start.x; j<=end.x; j++) newarr[j][start.y] = ch; } } // out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); // for (int i=0; i<n; i++) out.println(Arrays.toString(newarr[i])); for (int i=0; i<n; i++) for (int j=0; j<m; j++) if (arr[i][j] != newarr[i][j]) {out.printf("%s\n", "NO"); continue nextCase;} if (lastAlpha == -1) {out.printf("%s\n%d\n", "YES", 0); continue nextCase;} Pair filledCell = al.get(lastAlpha).get(0); for (int i=0; i<lastAlpha; i++) { if (al.get(i).size() == 0) { al.get(i).add(filledCell); al.get(i).add(filledCell); } } out.printf("%s\n", "YES"); out.printf("%d\n", lastAlpha+1); for (int i=0; i<=lastAlpha; i++) { out.printf("%d %d %d %d\n", al.get(i).get(0).x+1, al.get(i).get(0).y+1, al.get(i).get(al.get(i).size()-1).x+1, al.get(i).get(al.get(i).size()-1).y+1); } } } private static void run() throws Exception { // in = new Reader(); // in = new Reader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); in = oj ? new Reader() : new Reader(new FileReader("/home/raiden/Desktop/input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileWriter("/home/raiden/Desktop/output.txt")); long ti = System.currentTimeMillis(); solve(); out.flush(); if (!oj) System.out.println("\n"+(System.currentTimeMillis()-ti)+"ms"); } public static void main(String[] args) throws Exception {run();} }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
00c48ef4aa955bf609fba03fc94b45f7
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static Integer INT(String s){ return Integer.parseInt(s); } public static Long LONG(String s){ return Long.parseLong(s); } //==================================================================================================================== static class Node{ int i, j; Node(int i, int j){ this.i=i; this.j=j; } } public static void solve(char a[][], int n, int m){ Node start[]=new Node[26]; Node end[]=new Node[26]; boolean check=true; int last=-1; for(int k=25; k>=0; k--){ int i=0, j=0; boolean flag=false; for(i=0; i<n; i++){ for(j=0; j<m; j++) if(a[i][j]==(k+97)){ flag=true; break; } if(flag) break; } if(flag){ int end_j=m-1; for(; end_j>j; end_j--) if(a[i][end_j]==(k+97)) break; int end_i=n-1; for(; end_i>i; end_i--) if(a[end_i][j]==(k+97)) break; start[k]=new Node(i, j); if(end_j!=j){ end[k]=new Node(i, end_j); for(; j<=end_j; j++){ if(!(a[i][j]=='*' || a[i][j]==(k+97))) check=false; a[i][j]='*'; } } else{ end[k]=new Node(end_i, j); for(; i<=end_i; i++){ if(!(a[i][j]=='*' || a[i][j]==(k+97))) check=false; a[i][j]='*'; } } for(i=0; i<n; i++){ for(j=0; j<m; j++) if(a[i][j]==(k+97)){ check=false; break; } if(!check) break; } if(!check) break; if(last==-1) last=k; } else{ if(last!=-1){ start[k]=start[k+1]; end[k]=end[k+1]; } } } if(!check) System.out.println("NO"); else{ System.out.println("YES"); System.out.println(last+1); for(int i=0; i<=last; i++) System.out.println((start[i].i+1)+" "+(start[i].j+1)+" "+(end[i].i+1)+" "+(end[i].j+1)); } } public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(System.in); StringBuilder out=new StringBuilder(); int t=INT(br.readLine()); while(t--!=0){ String line[]=br.readLine().split("\\s"); int n=INT(line[0]), m=INT(line[1]); char a[][]=new char[n][m]; for(int i=0; i<n; i++) a[i]=br.readLine().toCharArray(); solve(a, n, m); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
99cae77ae257940dd9af13dfbb11ff8a
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); main: while (tc-- > 0) { int n = sc.nextInt(), m = sc.nextInt(); char[][] grid = new char[n][m]; for (int i = 0; i < n; i++) grid[i] = sc.next().toCharArray(); TreeMap<Integer, Snake> map = new TreeMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '.' || map.containsKey(grid[i][j] - 'a')) continue; char c = grid[i][j]; int x = i, y = j; for (int k = i + 1; k < n; k++) if (grid[k][j] == c) x = k; for (int k = j + 1; k < m; k++) if (grid[i][k] == c) y = k; if (x != i && j != y) { out.println("NO"); continue main; } map.put(c - 'a', new Snake(i, j, x, y)); } } if (map.isEmpty()) { out.println("YES"); out.println("0"); continue; } Snake tmp = map.get(map.lastKey()); int cnt = map.lastKey(); for (int i = 0; i <= cnt; i++) if (!map.containsKey(i)) map.put(i, tmp); char[][] test = new char[n][m]; for (char[] x : test) Arrays.fill(x, '.'); StringBuilder ans = new StringBuilder(); ans.append(map.size()); for (int i : map.keySet()) { Snake cur = map.get(i); ans.append(cur); for (int ii = cur.i; ii <= cur.x; ii++) test[ii][cur.j] = (char) ('a' + i); for (int jj = cur.j; jj <= cur.y; jj++) test[cur.i][jj] = (char) ('a' + i); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (test[i][j] != grid[i][j]) { out.println("NO"); continue main; } } } out.println("YES"); out.println(ans); } out.flush(); out.close(); } static class Snake { int i, j, x, y; public Snake(int i, int j, int x, int y) { this.i = i; this.j = j; this.x = x; this.y = y; } @Override public String toString() { return "\n" + (i + 1) + " " + (j + 1) + " " + (x + 1) + " " + (y + 1); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public 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 Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
41775eae127dbe9cdc3fb28fb035189d
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; public class CF1185E { static final int A = 26; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int[] i1 = new int[A]; int[] i2 = new int[A]; int[] j1 = new int[A]; int[] j2 = new int[A]; int t = Integer.parseInt(br.readLine()); while (t-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = 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); Arrays.fill(i1, n); Arrays.fill(i2, -1); Arrays.fill(j1, m); Arrays.fill(j2, -1); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { char c = cc[i][j]; if (c != '.') { int a = c - 'a'; if (i1[a] > i) i1[a] = i; if (i2[a] < i) i2[a] = i; if (j1[a] > j) j1[a] = j; if (j2[a] < j) j2[a] = j; } } int b = -1; boolean yes = true; out: for (int a = A - 1; a >= 0; a--) if (i1[a] <= i2[a] && j1[a] <= j2[a]) { if (b == -1) b = a; if (i1[a] < i2[a] && j1[a] < j2[a]) { yes = false; break; } char c = (char) (a + 'a'); for (int i = i1[a]; i <= i2[a]; i++) for (int j = j1[a]; j <= j2[a]; j++) { if (cc[i][j] != c && cc[i][j] != ' ') { yes = false; break out; } cc[i][j] = ' '; } } if (yes) { pw.println("YES"); pw.println(b + 1); for (int a = 0; a <= b; a++) { int c = i1[a] <= i2[a] && j1[a] <= j2[a] ? a : b; pw.println((i1[c] + 1) + " " + (j1[c] + 1) + " " + (i2[c] + 1) + " " + (j2[c] + 1)); } } else pw.println("NO"); } pw.close(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
e21a44f35d4d72777d70287d8cafdb4f
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; public class MainE { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); PrintWriter pw = new PrintWriter(System.out); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int H = sc.nextInt(); int W = sc.nextInt(); char[][] A = new char[H][]; for (int i = 0; i < H; i++) { A[i] = sc.next().toCharArray(); } int[][] ans = solve(H, W, A); if( ans != null ) { pw.println("YES"); pw.println(ans.length); for (int[] line : ans) { int h1 = line[0]+1; int w1 = line[1]+1; int h2 = line[2]+1; int w2 = line[3]+1; pw.println(h1 + " " + w1 + " " + h2 + " " + w2); } } else { pw.println("NO"); } } pw.flush(); } static int[][] solve(int H, int W, char[][] A) { Snake[] S = new Snake[26]; int hi = -1; for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { char c = A[h][w]; if( A[h][w] == '.' ) continue; int i = c-'a'; hi = Math.max(hi, i); if( S[i] == null ) { S[i] = new Point(h, w); continue; } Snake curr = S[i]; Snake next = curr.add(h, w); if( next == null ) return null; S[i] = next; } } if( hi == -1 ) return new int[0][]; char B = '#'; // ε¦₯当性をθͺΏγΉγ‚‹ for (int i = hi; i >= 0; i--) { Snake s = S[i]; if( s == null ) { // ι©ε½“γ«ε‘—γ‚Šγ€γΆγ•γ‚ŒγŸγ¨ζ€γ£γ¦γ‚ˆγ„ S[i] = S[i+1]; continue; } char c = (char)('a' + i); if( s instanceof Point ) { Point p = (Point) s; A[p.h][p.w] = B; } else if( s instanceof Vert ) { Vert v = (Vert) s; for (int h = v.h1; h <= v.h2; h++) { if( A[h][v.w] == '#' || A[h][v.w] == c) { // ok A[h][v.w] = '#'; } else { return null; } } } else if( s instanceof Hori ) { Hori ho = (Hori)s; for (int w = ho.w1; w <= ho.w2; w++) { if( A[ho.h][w] == '#' || A[ho.h][w] == c) { // ok A[ho.h][w] = '#'; } else { return null; } } } else { throw new RuntimeException("wtf"); } } int[][] ans = new int[hi+1][]; for (int i = 0; i <= hi; i++) { ans[i] = S[i].arr(); } return ans; } interface Snake { Snake add(int h, int w); int[] arr(); } static class Point implements Snake { int h, w; public Point(int h, int w) { this.h = h; this.w = w; } @Override public Snake add(int argh, int argw) { if( h == argh ) { return new Hori(h, Math.min(w, argw), Math.max(w, argw)); } else if( w == argw ) { return new Vert(Math.min(h, argh), Math.max(h, argh), w); } else { return null; // oops } } @Override public int[] arr() { return new int[]{h, w, h, w}; } } static class Vert implements Snake { int h1, h2, w; public Vert(int h1, int h2, int w) { this.h1 = h1; this.h2 = h2; this.w = w; } @Override public Snake add(int h, int w) { if( this.w != w ) return null; h1 = Math.min(h1, h); h2 = Math.max(h2, h); return this; } @Override public int[] arr() { return new int[]{h1, w, h2, w}; } } static class Hori implements Snake { int h, w1, w2; public Hori(int h, int w1, int w2) { this.h = h; this.w1 = w1; this.w2 = w2; } @Override public Snake add(int h, int w) { if( this.h != h ) return null; w1 = Math.min(w, w1); w2 = Math.max(w, w2); return this; } @Override public int[] arr() { return new int[]{h, w1, h, w2}; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(as[i]); } pw.println(); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg == null) j.add("null"); else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } static void printSingleLine(int[] array) { PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < array.length; i++) { if (i != 0) pw.print(" "); pw.print(array[i]); } pw.println(); pw.flush(); } static int lowerBound(int[] array, int value) { int lo = 0, hi = array.length, mid; while (lo < hi) { mid = (hi + lo) / 2; if (array[mid] < value) lo = mid + 1; else hi = mid; } return lo; } static int upperBound(int[] array, int value) { int lo = 0, hi = array.length, mid; while (lo < hi) { mid = (hi + lo) / 2; if (array[mid] <= value) lo = mid + 1; else hi = mid; } return lo; } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
b645d9ad46654a21994e0290eb703fea
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; import java.lang.Math.*; public class EPolycarpandSnakes { static HashSet done = new HashSet(); static int []mark = new int[26]; 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(); outter: while (n-->0){ int check =0; int mx=-1; done.clear(); for(int j=0;j<26;j++) mark[j]=0; int r= in.nextInt(); int c = in.nextInt(); int [][] ans = new int[26][4]; String[] paper = new String[r]; // System.out.println("row"+r+"col"+c); for(int j=0;j<r;j++){ paper[j]= in.next(); } char cur; for(int j=0;j<r;j++){ for(int k=0;k<c;k++){ cur =paper[j].charAt(k); String word = Integer.toString(cur)+"-"+Integer.toString(j)+'-'+Integer.toString(k); if(cur!='.'){ int idex = (int)cur-(int)('a'); mx = Math.max(mx,idex); if (mark[idex] ==0) { mark[idex]=1; int a1 = walkDown(paper,j,k,paper[j].charAt(k)); int a2 = walkright(paper,j,k,paper[j].charAt(k)); if (a1!=-1 & a2 !=-1){ System.out.println("NO"); continue outter; } if (a1>-1){ ans[idex][0]=j+1;ans[idex][1]=k+1;ans[idex][2]=a1+1;ans[idex][3]=k+1; char compare; for(int l=j;l<=a1;l++){ compare = paper[l].charAt(k); if (compare<cur) { System.out.println("NO"); continue outter; } word = Integer.toString(cur)+"-"+Integer.toString(l)+'-'+Integer.toString(k); done.add(word); } } else if (a2>-1){ char compare; ans[idex][0]=j+1;ans[idex][1]=k+1;ans[idex][2]=j+1;ans[idex][3]=a2+1; for(int l=k;l<=a2;l++){ compare = paper[j].charAt(l); if (compare<cur) { System.out.println("NO"); continue outter; } word = Integer.toString(cur)+"-"+Integer.toString(j)+'-'+Integer.toString(l); done.add(word); } } else { word = Integer.toString(cur)+"-"+Integer.toString(j)+'-'+Integer.toString(k); done.add(word); ans[idex][0]=j+1;ans[idex][1]=k+1;ans[idex][2]=j+1;ans[idex][3]=k+1; } } else{ if(!done.contains(word)){ System.out.println("NO"); continue outter; } } } } } int r1=-1;int c1=-1; for (int ii=25;ii>-1;ii--){ if (mark[ii]>0){ r1=ans[ii][0]; c1= ans[ii][1]; break; } } System.out.println("YES"); if (mx>-1){ System.out.println(mx+1); for(int ii=0;ii<=mx;ii++){ if (mark[ii]>0){ System.out.println(ans[ii][0]+" "+ans[ii][1]+" "+ans[ii][2]+" "+ans[ii][3]); } else System.out.println((r1)+" "+(c1)+" "+(r1)+" "+(c1)); } } else System.out.println(0); } } public static int walkDown(String[] a,int row ,int col,char c){ int v = -1; for(int i=row+1;i<a.length;i++){ if (a[i].charAt(col) == c) v=i; } return v; } public static int walkright(String[] a,int row ,int col,char c){ int v = -1; for(int i=col+1;i<a[0].length();i++){ // System.out.println("Need:"+c); // System.out.println(a[row].charAt(i)+":"+(a[row].charAt(i) == c)); if (a[row].charAt(i) == c) v=i; } return v; } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
3620fe8cd64914a35de96e7e79418163
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class zz{ public static void main(String[] args) throws IOException{ MScanner sc = new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); char[][]in; int[][]small=new int[2][26]; int[][]big=new int[2][26]; o:while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); in=new char[n][m]; for(int i=0;i<n;i++)in[i]=sc.nextLine().toCharArray(); Arrays.fill(small[0],-1); Arrays.fill(small[1],-1); Arrays.fill(big[0],-1); Arrays.fill(big[1],-1); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(in[i][j]!='.') { int idx=in[i][j]-'a'; if(small[0][idx]==-1) { small[0][idx]=i;small[1][idx]=j; } big[0][idx]=i;big[1][idx]=j; } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(in[i][j]!='.') { int idx=in[i][j]-'a'; if(i>=small[0][idx] && i<=big[0][idx]) { } else { pw.println("NO");continue o; } if(j>=small[1][idx] && j<=big[1][idx]) { } else { pw.println("NO");continue o; } } } } LinkedList<Triple>ans=new LinkedList<Triple>(); int last=-1; for(int i=25;i>=0;i--) { if(small[0][i]!=-1) { if(big[0][i]-small[0][i]!=0 && big[1][i]-small[1][i]!=0) { pw.println("NO");continue o; } last=i; for(int o=small[0][i];o<=big[0][i];o++) { for(int k=small[1][i];k<=big[1][i];k++) { if(in[o][k]=='.' || (int)(in[o][k]-'a')<i) { pw.println("NO");continue o; } } } ans.addFirst(new Triple(small[0][i]+1,small[1][i]+1,big[0][i]+1,big[1][i]+1)); } else { if(last!=-1) { ans.addFirst(new Triple(small[0][last]+1,small[1][last]+1,big[0][last]+1,big[1][last]+1)); } } } pw.println("YES"); pw.println(ans.size()); while(!ans.isEmpty()) { pw.println(ans.removeFirst()); } } pw.flush(); } static class Triple implements Comparable<Triple> { int i,j,cost,color; Triple(int x, int y, int z,int o){i = x; j = y; cost = z;color=o;} public int compareTo(Triple t) { return this.cost - t.cost; } public String toString() { return i+" "+j+" "+cost+" "+color; } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
08e11ea688a88acc78302b49988332c6
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; /******************************\ * The solution is at the top * * * * Created by : azhar556 * \******************************/ public class B { static class Pair { int a, b; Pair (int a, int b) { this.a = a; this.b = b; } } static class Info { Character patokan; Vector<Pair> cart = new Vector<>(); String stringPair () { return String.valueOf((cart.get(0).a + 1) + " " + (cart.get(0).b + 1) + " " + (cart.lastElement().a + 1) + " " + (cart.lastElement().b + 1)); } } static void solve() { final String yes = "YES"; final String no = "NO"; int n = ni(); int m = ni(); int notok = -1; char[][] grid = new char[n][]; Info[] alp = new Info[26]; boolean gabisa = false; for (int i = 0; i < n; i++) { String masuk = ns(); grid[i] = masuk.toCharArray(); for (int j = 0; j < m && !gabisa; j++) { char nowChar = grid[i][j]; if (nowChar != '.') { notok = Math.max(notok, nowChar - 'a'); if (alp[nowChar - 'a'] == null) alp[nowChar - 'a'] = new Info(); Vector<Pair> thisCart = alp[nowChar - 'a'].cart; if (thisCart.size() > 1) { if (alp[nowChar - 'a'].patokan == 'i' && thisCart.get(0).a != i) { gabisa = true; } else if (alp[nowChar - 'a'].patokan == 'j' && thisCart.get(0).b != j) { gabisa = true; } } else if (thisCart.size() == 1) { if (thisCart.get(0).a == i) { alp[nowChar - 'a'].patokan = 'i'; } else if (thisCart.get(0).b == j) { alp[nowChar - 'a'].patokan = 'j'; } else { gabisa = true; } } thisCart.add(new Pair(i, j)); } } } if (gabisa) { out.println(no); return; } Pair sisa = null; for (int i = 0; i < 26; i++) { if (alp[i] != null) { sisa = new Pair(alp[i].cart.get(0).a + 1, alp[i].cart.get(0).b + 1); if (alp[i].patokan == null) continue; Vector<Pair> thisCart = alp[i].cart; if (alp[i].patokan == 'i') { for (int cartB = thisCart.get(0).b; cartB <= thisCart.lastElement().b; cartB++) { if (grid[thisCart.get(0).a][cartB] - 'a' < i) { out.println(no); return; } } } else { for (int cartA = thisCart.get(0).a; cartA <= thisCart.lastElement().a; cartA++) { if (grid[cartA][thisCart.get(0).b] - 'a' < i) { out.println(no); return; } } } } } out.println(yes + "\n" + (notok + 1)); for (int i = 0; i <= notok; i++) { if (alp[i] != null) { out.println(alp[i].stringPair()); } else { if (sisa != null) out.println(sisa.a + " " + sisa.b + " " + sisa.a + " " + sisa.b); } } } public static void main(String[] args) { long time = System.currentTimeMillis(); int t = ni(); // t = 1; while (t-- > 0) solve(); err.println("Time elapsed : " + (System.currentTimeMillis() - time) / 1000F + " s."); err.close(); out.close(); } static int[] radixSort(int[] f){ return radixSort(f, f.length); } static 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 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static PrintWriter err = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err))); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token; static boolean hasMoreTokens () { String sample = null; try { sample = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return sample == null ? false : true; } static String ns() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } static char nc() { return Character.valueOf(ns().charAt(0)); } static int ni() { return Integer.parseInt(ns()); } static double nd() { return Double.parseDouble(ns()); } static long nl() { return Long.parseLong(ns()); } } // Collections Arrays Math // Vector HashSet TreeSet HashMap TreeMap ArrayDeque
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
2c9711c6e40f35df109ccd73a14ed6f2
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
//package cf568d2; import java.util.*; public class E { public static void main(String[]args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int w=0;w<t;w++){ boolean[]cont=new boolean[26]; boolean ok=true; int n=sc.nextInt(),m=sc.nextInt(); sc.nextLine(); char[][]grid=new char[n][m]; LinkedList<String>snakes=new LinkedList<String>(); for(int i=0;i<n;i++) { grid[i]=sc.nextLine().toCharArray(); for(int j=0;j<m;j++) if(grid[i][j]-'a'>=0&&grid[i][j]-'a'<26) cont[grid[i][j]-'a']=true; } int let=25; while(let>=0&&!cont[let]) let--; for(int l=let;l>=0;l--){ if(ok) { TreeSet<Integer> rows = new TreeSet<Integer>(), cols = new TreeSet<Integer>(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (grid[i][j] == l + 'a') { rows.add(i); cols.add(j); } if (rows.size() == 1) { int start = cols.first(), end = cols.last(), row = rows.first(); for (int j = start; j <= end; j++) { if (grid[row][j] - 'a' < l || grid[row][j] - 'a' >= 26) ok = false; } snakes.addFirst((row+1)+" "+(start+1)+" "+(row+1)+" "+(end+1)); } else if(cols.size()==1){ int start = rows.first(), end = rows.last(), col = cols.first(); for (int i = start; i <= end; i++) { if (grid[i][col] - 'a' < l || grid[i][col] - 'a' >= 26) ok = false; } snakes.addFirst((start+1)+" "+(col+1)+" "+(end+1)+" "+(col+1)); } else if(rows.isEmpty()&&cols.isEmpty()) snakes.addFirst(snakes.getFirst()); else ok=false; } } System.out.println(ok?"YES":"NO"); if(ok){ System.out.println(snakes.size()); for(String s:snakes) System.out.println(s); } } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
47fa9243d6792941b4c44ecf9b821e6e
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; public class A { static char [][]comp; static void draw(int []x,int alpha) { int i1=x[0],j1=x[1],i2=x[2],j2=x[3]; for(int i=i1;i<=i2;i++) for(int j=j1;j<=j2;j++) comp[i][j]=(char)('a'+alpha); } static int ALPHA=26; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc=sc.nextInt(); while(tc-->0) { int n=sc.nextInt(),m=sc.nextInt(); char [][]grid=new char[n][m]; int [][]first=new int [ALPHA][],draw=new int [ALPHA][4]; comp=new char [n][m]; for(int i=0;i<n;i++) { grid[i]=sc.next().toCharArray(); for(int j=0;j<m;j++) { comp[i][j]='.'; if(grid[i][j]=='.') continue; int idx=grid[i][j]-'a'; if(first[idx]==null) first[idx]=new int [] {i,j}; } } for(int alpha=0;alpha<ALPHA;alpha++) { if(first[alpha]==null) continue; int i1=first[alpha][0],j1=first[alpha][1]; int i2=i1,j2=j1; for(int j=j1;j<m;j++) if(grid[i1][j]-'a'==alpha) j2=j; for(int i=i1+1;i<n;i++) if(grid[i][j1]-'a'==alpha) { i2=i; j2=j1; } draw[alpha]=new int [] {i1,j1,i2,j2}; // System.out.println(alpha); // System.out.println(Arrays.toString(first[alpha])); // // System.out.println(Arrays.toString(draw[alpha])); } int maxAlpha=-1; for(int alpha=ALPHA-1;alpha>=0;alpha--) { if(first[alpha]==null) { if(maxAlpha==-1) continue; draw[alpha]=draw[alpha+1]; } else if(maxAlpha==-1) { maxAlpha=alpha; } } for(int alpha=0;alpha<=maxAlpha;alpha++) { draw(draw[alpha], alpha); } boolean equal=true; for(int i=0;i<n;i++) for(int j=0;j<m;j++) equal&=grid[i][j]==comp[i][j]; if(!equal) { out.println("NO"); continue; } out.println("YES"); out.println(maxAlpha+1); for(int alpha=0;alpha<=maxAlpha;alpha++) { int []x=draw[alpha]; out.println((x[0]+1)+" "+(x[1]+1)+" "+(x[2]+1)+" "+(x[3]+1)); } } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
adcb3428134e265eb72a66d2070ae6e9
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; public class PolycarpAndSnakes { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(f.readLine()); for(int x = 0; x < t; x++){ StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[][] arr = new char[n][m]; char largest = '.'; for(int i = 0; i < n; i++){ String temp = f.readLine(); for(int j = 0; j < m; j++){ arr[i][j] = temp.charAt(j); if(arr[i][j] > largest) largest = arr[i][j]; } } if(largest == '.'){ out.println("YES"); out.println(0); continue; } int largestI = (int)(largest-'a')+1; boolean no = false; StringBuilder ans = new StringBuilder(); for(; largest >= 'a'; largest--){ int leftR = Integer.MAX_VALUE; int leftC = Integer.MAX_VALUE; int rightR = Integer.MIN_VALUE; int rightC = Integer.MIN_VALUE; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(arr[i][j] == largest){ leftR = Math.min(leftR, i); leftC = Math.min(leftC, j); rightR = Math.max(rightR, i); rightC = Math.max(rightC, j); } } } if(leftR == Integer.MAX_VALUE){ boolean found = false; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(arr[i][j] == '*'){ ans.append((i+1) + " " + (j+1) + " " + (i+1) + " " + (j+1)); ans.append('\n'); found = true; break; } } if(found) break; } continue; } if(!(leftR == rightR || leftC == rightC)){ out.println("NO"); no = true; break; } for(int i = leftR; i <= rightR; i++){ for(int j = leftC; j <= rightC; j++){ if(!(arr[i][j] == largest || arr[i][j] == '*')){ out.println("NO"); no = true; break; } } if(no) break; } ans.append((leftR+1) + " " + (leftC+1) + " " + (rightR+1) + " " +(rightC+1)); ans.append("\n"); if(no) break; for(int i = leftR; i <= rightR; i++){ for(int j = leftC; j <= rightC; j++){ arr[i][j] = '*'; } } } if(no) continue; out.println("YES"); out.println(largestI); String[] outarr = ans.toString().trim().split("\n"); for(int i = largestI-1; i >= 0; i--) { out.println(outarr[i]); } } out.close(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
731cb8aac8f50d3611d2e0e7691da0ff
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static long mod= (int) (1e9 +9); static int n; static StringBuilder sol; static class pair implements Comparable<pair>{ int x,y; public pair(int a,int b){ x=a; y=b; } @Override public int compareTo(pair pair) { return x-pair.x; } public String toString(){ return x+" "+y; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); char[][] in = new char[n][m]; for (int i = 0; i < n; i++) in[i] = sc.nextLine().toCharArray(); pair[] start = new pair[26]; pair[] end = new pair[26]; boolean is = true; int endc = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (in[i][j] != '.') { int cur = in[i][j] - 'a'; endc = Math.max(endc, cur); if (start[cur] == null) { start[cur] = new pair(i, j); end[cur] = start[cur]; } else end[cur] = new pair(i, j); } } } char[][] ans = new char[n][m]; int pre = 0; sol = new StringBuilder(); int all = endc + 1; for (char[] x : ans) Arrays.fill(x, '.'); for (int k = 0; k <= endc; k++) { char now = (char) ('a' + k); if (start[k] != null) { if (start[k].y == end[k].y) { for (int l = start[k].x; l <= end[k].x; l++) { ans[l][start[k].y] = now; } StringBuilder th = new StringBuilder(); th.append(start[k].x + 1+" "); th.append(start[k].y + 1+" "); th.append(end[k].x + 1+" "); th.append(end[k].y + 1+" "); th.append("\n"); sol.append(th); while (pre > 0) { sol.append(th); pre--; } } else if (start[k].x == end[k].x) { for (int l = start[k].y; l <= end[k].y; l++) { ans[start[k].x][l] = now; } StringBuilder th = new StringBuilder(); th.append(start[k].x + 1+" "); th.append(start[k].y + 1+" "); th.append(end[k].x + 1+" "); th.append(end[k].y + 1+" "); th.append("\n"); sol.append(th); while (pre > 0) { sol.append(th); pre--; } } else { is = false; } } else { pre++; } } // pw.println(Arrays.deepToString(end)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (in[i][j] != ans[i][j]) { is = false; break; } } } if (is) { pw.println("YES"); pw.println(all); pw.println(sol); } else pw.println("NO"); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
3e6500effbf26994880de5b2e76a62bf
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
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.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); EPolikarpIZmeiki solver = new EPolikarpIZmeiki(); solver.solve(1, in, out); out.close(); } static class EPolikarpIZmeiki { public void solve(int testNumber, InputReader in, PrintWriter out) { int tt = in.nextInt(); outer: for (int t = 0; t < tt; t++) { int n = in.nextInt(); int m = in.nextInt(); int[][] c = new int['z' - 'a' + 1][4]; // rmin rmax cmin cmax for (int i = 0; i <= 'z' - 'a'; i++) { for (int h = 0; h < 4; h++) { c[i][h] = h % 2 == 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } } char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { String s = in.next(); for (int h = 0; h < m; h++) { a[i][h] = s.charAt(h); if (a[i][h] == '.') { continue; } int charIdx = a[i][h] - 'a'; c[charIdx][0] = Math.min(c[charIdx][0], i); c[charIdx][1] = Math.max(c[charIdx][1], i); c[charIdx][2] = Math.min(c[charIdx][2], h); c[charIdx][3] = Math.max(c[charIdx][3], h); } } List<EPolikarpIZmeiki.Item> ans = new ArrayList<>(); for (int charIdx = 'z' - 'a'; charIdx >= 0; charIdx--) { if (c[charIdx][0] == Integer.MAX_VALUE) { if (!ans.isEmpty()) { ans.add(ans.get(0)); } continue; } if (c[charIdx][0] != c[charIdx][1] && c[charIdx][2] != c[charIdx][3]) { out.println("NO"); continue outer; } for (int i = c[charIdx][0]; i <= c[charIdx][1]; i++) { for (int h = c[charIdx][2]; h <= c[charIdx][3]; h++) { if (a[i][h] == '.' || a[i][h] - 'a' < charIdx) { out.println("NO"); continue outer; } } } ans.add(new EPolikarpIZmeiki.Item(c[charIdx][0] + 1, c[charIdx][1] + 1, c[charIdx][2] + 1, c[charIdx][3] + 1)); } out.println("YES"); out.println(ans.size()); for (int i = ans.size() - 1; i >= 0; i--) { out.println(String.format("%d %d %d %d", ans.get(i).rl, ans.get(i).cl, ans.get(i).rr, ans.get(i).cr)); } } } static class Item { int rl; int rr; int cl; int cr; public Item(int rl, int rr, int cl, int cr) { this.rl = rl; this.rr = rr; this.cl = cl; this.cr = cr; } } } 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
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
3dbede8c43bb9544cec6380825e5fab3
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Random; import java.util.TreeSet; public final class CF_568_D2_E { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int CX=26; int MX=2002; int T=reader.readInt(); for (int t=0;t<T;t++) { int n=reader.readInt(); int m=reader.readInt(); int[] minj=new int[CX]; int[] maxj=new int[CX]; int[] mini=new int[CX]; int[] maxi=new int[CX]; Arrays.fill(minj, MX); Arrays.fill(mini, MX); Arrays.fill(maxi, -1); Arrays.fill(maxj, -1); String[] map=new String[n]; for (int i=0;i<n;i++) { map[i]=reader.readString(); for (int j=0;j<m;j++) { char c=map[i].charAt(j); if (c!='.') { int x=c-'a'; if (minj[x]>j) minj[x]=j; if (maxj[x]<j) maxj[x]=j; if (mini[x]>i) mini[x]=i; if (maxi[x]<i) maxi[x]=i; //log(mini[x]+" "+maxi[x]); } } } boolean ok=true; for (int u=0;u<CX;u++) { if (maxi[u]>mini[u] && maxj[u]>minj[u]) { ok=false; break; } } if (ok) { loop:for (int u=0;u<CX;u++) { for (int i=mini[u];i<=maxi[u];i++) for (int j=minj[u];j<=maxj[u];j++) { if (map[i].charAt(j)=='.') { ok=false; break loop; } else { int v=map[i].charAt(j)-'a'; if (v<u) { ok=false; break loop; } } } } } if (!ok) output("NO"); else { output("YES"); String ans=""; String prev=""; int cn=0; for (int u=CX-1;u>=0;u--) { if (maxi[u]>=0) { if (cn==0) cn=u+1; prev=(mini[u]+1)+" "+(minj[u]+1)+" "+(maxi[u]+1)+" "+(maxj[u]+1)+"\n"; } ans=prev+ans; } output(cn); output(ans); } } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
7a0153efb0564f20ea7d8f0666a07919
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
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 * * @author revanth */ 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); EPolycarpAndSnakes solver = new EPolycarpAndSnakes(); solver.solve(1, in, out); out.close(); } static class EPolycarpAndSnakes { public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(), n, m, x, y; char[][] a; int[] minh = new int[26]; int[] minv = new int[26]; int[] maxh = new int[26]; int[] maxv = new int[26]; String s; g: while (t-- > 0) { Arrays.fill(minh, 2000); Arrays.fill(minv, 2000); Arrays.fill(maxh, 0); Arrays.fill(maxv, 0); y = -1; n = in.nextInt(); m = in.nextInt(); a = new char[n][m]; for (int i = 0; i < n; i++) { s = in.nextString(); a[i] = s.toCharArray(); for (int j = 0; j < m; j++) { if (a[i][j] == '.') continue; x = a[i][j] - 'a'; y = Math.max(y, x); minh[x] = Math.min(minh[x], i); minv[x] = Math.min(minv[x], j); maxh[x] = Math.max(maxh[x], i); maxv[x] = Math.max(maxv[x], j); } } for (int i = y; i >= 0; i--) { if (minh[i] == 2000) { minh[i] = minh[i + 1]; minv[i] = minv[i + 1]; maxh[i] = maxh[i + 1]; maxv[i] = maxv[i + 1]; continue; } if (minh[i] == maxh[i]) { for (int j = minv[i]; j <= maxv[i]; j++) { x = a[minh[i]][j] - 'a'; if (a[minh[i]][j] == '.' || (a[minh[i]][j] != '.' && x < i)) { out.println("NO"); continue g; } } } else if (minv[i] == maxv[i]) { for (int j = minh[i]; j <= maxh[i]; j++) { x = a[j][minv[i]] - 'a'; if (a[j][minv[i]] == '.' || (a[j][minv[i]] != '.' && x < i)) { out.println("NO"); continue g; } } } else { out.println("NO"); continue g; } } out.println("YES"); out.println(y + 1); for (int i = 0; i <= y; i++) out.println((minh[i] + 1) + " " + (minv[i] + 1) + " " + (maxh[i] + 1) + " " + (maxv[i] + 1)); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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(); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
db2987b52e8ca62b640650c47f338d31
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author real */ 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(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char ar[][] = new char[n][m]; char max = 'a' - 1; for (int i = 0; i < n; i++) { String str = in.readString(); for (int j = 0; j < str.length(); j++) { ar[i][j] = str.charAt(j); if (ar[i][j] != '.' && ar[i][j] > max) { max = ar[i][j]; } } } if (max < 'a') { out.println("YES"); out.println(0); return; } ArrayList<pair> list[] = new ArrayList[(max - 'a') + 1]; for (int i = 0; i < list.length; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ar[i][j] != '.') { list[ar[i][j] - 'a'].add(new pair(i, j)); } } } char ans[][] = new char[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[i][j] = '.'; } } for (int i = 0; i <= max - 'a'; i++) { if (list[i].size() == 0) { continue; } pair start = list[i].get(0); pair end = list[i].get(list[i].size() - 1); if (start.r == end.r) { for (int j = start.c; j <= end.c; j++) { ans[start.r][j] = (char) ('a' + i); } } else { if (start.c == end.c) { for (int j = start.r; j <= end.r; j++) { ans[j][start.c] = (char) ('a' + i); } } else { out.println("NO"); return; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ar[i][j] != ans[i][j]) { out.println("NO"); return; } } } out.println("YES"); out.println(list.length); pair answer[][] = new pair[list.length][2]; pair prevs = null, preve = null; for (int i = list.length - 1; i >= 0; i--) { pair start, end; if (list[i].size() == 0) { start = prevs; end = preve; } else { start = list[i].get(0); end = list[i].get(list[i].size() - 1); } prevs = start; preve = end; // out.println((start.r+1) + " " + (start.c+1) + " " + (end.r+1) + " " + (end.c+1)); answer[i][0] = start; answer[i][1] = end; } for (int i = 0; i < list.length; i++) { pair start = answer[i][0]; pair end = answer[i][1]; out.println((start.r + 1) + " " + (start.c + 1) + " " + (end.r + 1) + " " + (end.c + 1)); } } class pair { int r; int c; pair(int r, int c) { this.r = r; this.c = c; } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mist[[[[[[pakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things // for test cases make sure println(); ;) //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ 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 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 next() { String str = readString(); return str; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
69037591f67a56b62265aae33109c55e
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { final int MAX = 26; final char EMPTY = '.'; final int UNDEF = -1; int t = in.nextInt(); outer: while (t-- > 0) { int sizeI = in.nextInt(); int sizeJ = in.nextInt(); char[][] a = new char[sizeI][sizeJ]; for (int i = 0; i < sizeI; i++) for (int j = 0; j < sizeJ; j++) a[i][j] = in.nextCharacter(); Snake[] s = new Snake[MAX]; for (int i = 0; i < sizeI; i++) { for (int j = 0; j < sizeJ; j++) { if (a[i][j] != EMPTY) { int idx = a[i][j] - 'a'; if (s[idx] == null) s[idx] = new Snake(new Pos(i, j)); else s[idx].end = new Pos(i, j); if (!s[idx].isValid()) { out.println("NO"); continue outer; } } } } int lastIdx = UNDEF; Pos lastPos = null; for (int i = 0; i < MAX; i++) { if (s[i] == null) continue; if (s[i].end == null) s[i].end = new Pos(s[i].start); lastIdx = i; lastPos = new Pos(s[i].end); } for (int i = 0; i < lastIdx; i++) if (s[i] == null) s[i] = new Snake(lastPos, lastPos); char[][] check = new char[sizeI][sizeJ]; for (int i = 0; i < sizeI; i++) for (int j = 0; j < sizeJ; j++) check[i][j] = EMPTY; for (int c = 0; c < MAX; c++) { if (s[c] == null) continue; char label = (char) (c + 'a'); if (s[c].start.i == s[c].end.i) for (int j = s[c].start.j; j <= s[c].end.j; j++) check[s[c].start.i][j] = label; else for (int i = s[c].start.i; i <= s[c].end.i; i++) check[i][s[c].start.j] = label; } for (int i = 0; i < sizeI; i++) { for (int j = 0; j < sizeJ; j++) { if (check[i][j] != a[i][j]) { out.println("NO"); continue outer; } } } out.println("YES"); out.println(lastIdx + 1); for (Snake snake : s) if (snake != null) out.println(snake); } } private class Pos { private int i; private int j; private Pos(int i, int j) { this.i = i; this.j = j; } private Pos(Pos pos) { i = pos.i; j = pos.j; } public String toString() { return (i + 1) + " " + (j + 1); } } private class Snake { private Pos start; private Pos end; private Snake(Pos start) { this.start = start; } private Snake(Pos start, Pos end) { this.start = start; this.end = end; } private boolean isValid() { if (end == null) return true; return start.i == end.i || start.j == end.j; } public String toString() { return start + " " + end; } } } 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 println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
51e7b0a9dd99b91c95d13cac0be04869
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; public class CFContest { public static void main(String[] args) throws Exception { boolean local = System.getProperty("ONLINE_JUDGE") == null; boolean async = false; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e9 + 2; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { int t = io.readInt(); while (t-- > 0) solve(); } int n; int[][] data; char[][] mat = new char[2000][2000]; int[] cntOfChar = new int[128]; int[] l = new int[128]; int[] r = new int[128]; int[] u = new int[128]; int[] d = new int[128]; int[][] ans = new int[128][4]; public void solve() { int n = io.readInt(); int m = io.readInt(); for (int i = 0; i < n; i++) { io.readString(mat[i], 0); } Arrays.fill(cntOfChar, 0); Arrays.fill(l, m); Arrays.fill(r, -1); Arrays.fill(u, n); Arrays.fill(d, -1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char c = mat[i][j]; cntOfChar[c]++; l[c] = Math.min(l[c], j); r[c] = Math.max(r[c], j); u[c] = Math.min(u[c], i); d[c] = Math.max(d[c], i); } } int maxValidCharacter = 'a' - 1; for (int i = 'a'; i <= 'z'; i++) { if (cntOfChar[i] == 0) { continue; } maxValidCharacter = Math.max(maxValidCharacter, i); if (l[i] != r[i] && u[i] != d[i]) { io.cache.append("NO\n"); return; } if (!checkSnake((char) i)) { io.cache.append("NO\n"); return; } } io.cache.append("YES\n"); io.cache.append(maxValidCharacter - 'a' + 1).append('\n'); for (int i = maxValidCharacter; i >= 'a'; i--) { if (cntOfChar[i] == 0) { for (int j = 0; j < 4; j++) { ans[i][j] = ans[i + 1][j]; } continue; } ans[i][0] = u[i]; ans[i][1] = l[i]; ans[i][2] = d[i]; ans[i][3] = r[i]; } for (int i = 'a'; i <= maxValidCharacter; i++) { for (int j = 0; j < 4; j++) { io.cache.append(ans[i][j] + 1).append(' '); } io.cache.append('\n'); } } public boolean checkSnake(char c) { if (l[c] == r[c]) { for (int i = u[c]; i <= d[c]; i++) { char item = mat[i][l[c]]; if (item == '.' || item < c) { return false; } } return true; } else { for (int i = l[c]; i <= r[c]; i++) { char item = mat[u[c]][i]; if (item == '.' || item < c) { return false; } } return true; } } } public static class Randomized { static Random random = new Random(); public static double nextDouble(double min, double max) { return random.nextDouble() * (max - min) + min; } public static void randomizedArray(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(double[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); double tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(float[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); float tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static <T> void randomizedArray(T[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); T tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } public static class Splay implements Cloneable { public static final Splay NIL = new Splay(); static { NIL.left = NIL; NIL.right = NIL; NIL.father = NIL; NIL.size = 0; NIL.key = Integer.MIN_VALUE; NIL.sum = 0; } Splay left = NIL; Splay right = NIL; Splay father = NIL; int size = 1; int key; long sum; public static void splay(Splay x) { if (x == NIL) { return; } Splay y, z; while ((y = x.father) != NIL) { if ((z = y.father) == NIL) { y.pushDown(); x.pushDown(); if (x == y.left) { zig(x); } else { zag(x); } } else { z.pushDown(); y.pushDown(); x.pushDown(); if (x == y.left) { if (y == z.left) { zig(y); zig(x); } else { zig(x); zag(x); } } else { if (y == z.left) { zag(x); zig(x); } else { zag(y); zag(x); } } } } x.pushDown(); x.pushUp(); } public static void zig(Splay x) { Splay y = x.father; Splay z = y.father; Splay b = x.right; y.setLeft(b); x.setRight(y); z.changeChild(y, x); y.pushUp(); } public static void zag(Splay x) { Splay y = x.father; Splay z = y.father; Splay b = x.left; y.setRight(b); x.setLeft(y); z.changeChild(y, x); y.pushUp(); } public void setLeft(Splay x) { left = x; x.father = this; } public void setRight(Splay x) { right = x; x.father = this; } public void changeChild(Splay y, Splay x) { if (left == y) { setLeft(x); } else { setRight(x); } } public void pushUp() { if (this == NIL) { return; } size = left.size + right.size + 1; sum = left.sum + right.sum + key; } public void pushDown() { } public static int toArray(Splay root, int[] data, int offset) { if (root == NIL) { return offset; } offset = toArray(root.left, data, offset); data[offset++] = root.key; offset = toArray(root.right, data, offset); return offset; } public static void toString(Splay root, StringBuilder builder) { if (root == NIL) { return; } root.pushDown(); toString(root.left, builder); builder.append(root.key).append(','); toString(root.right, builder); } public Splay clone() { try { return (Splay) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static Splay cloneTree(Splay splay) { if (splay == NIL) { return NIL; } splay = splay.clone(); splay.left = cloneTree(splay.left); splay.right = cloneTree(splay.right); return splay; } public static Splay add(Splay root, Splay node) { if (root == NIL) { return node; } Splay p = root; while (root != NIL) { p = root; root.pushDown(); if (root.key < node.key) { root = root.right; } else { root = root.left; } } if (p.key < node.key) { p.setRight(node); } else { p.setLeft(node); } p.pushUp(); splay(node); return node; } /** * Make the node with the minimum key as the root of tree */ public static Splay selectMinAsRoot(Splay root) { if (root == NIL) { return root; } root.pushDown(); while (root.left != NIL) { root = root.left; root.pushDown(); } splay(root); return root; } /** * Make the node with the maximum key as the root of tree */ public static Splay selectMaxAsRoot(Splay root) { if (root == NIL) { return root; } root.pushDown(); while (root.right != NIL) { root = root.right; root.pushDown(); } splay(root); return root; } /** * delete root of tree, then merge remain nodes into a new tree, and return the new root */ public static Splay deleteRoot(Splay root) { root.pushDown(); Splay left = splitLeft(root); Splay right = splitRight(root); return merge(left, right); } /** * detach the left subtree from root and return the root of left subtree */ public static Splay splitLeft(Splay root) { root.pushDown(); Splay left = root.left; left.father = NIL; root.setLeft(NIL); root.pushUp(); return left; } /** * detach the right subtree from root and return the root of right subtree */ public static Splay splitRight(Splay root) { root.pushDown(); Splay right = root.right; right.father = NIL; root.setRight(NIL); root.pushUp(); return right; } public static Splay merge(Splay a, Splay b) { if (a == NIL) { return b; } if (b == NIL) { return a; } a = selectMaxAsRoot(a); a.setRight(b); a.pushUp(); return a; } public static Splay selectKthAsRoot(Splay root, int k) { if (root == NIL) { return NIL; } Splay trace = root; Splay father = NIL; while (trace != NIL) { father = trace; trace.pushDown(); if (trace.left.size >= k) { trace = trace.left; } else { k -= trace.left.size + 1; if (k == 0) { break; } else { trace = trace.right; } } } splay(father); return father; } public static Splay selectKeyAsRoot(Splay root, int k) { if (root == NIL) { return NIL; } Splay trace = root; Splay father = NIL; Splay find = NIL; while (trace != NIL) { father = trace; trace.pushDown(); if (trace.key > k) { trace = trace.left; } else { if (trace.key == k) { find = trace; trace = trace.left; } else { trace = trace.right; } } } splay(father); if (find != NIL) { splay(find); return find; } return father; } public static Splay bruteForceMerge(Splay a, Splay b) { if (a == NIL) { return b; } else if (b == NIL) { return a; } if (a.size < b.size) { Splay tmp = a; a = b; b = tmp; } a = selectMaxAsRoot(a); int k = a.key; while (b != NIL) { b = selectMinAsRoot(b); if (b.key >= k) { break; } Splay kickedOut = b; b = deleteRoot(b); a = add(a, kickedOut); } return merge(a, b); } public static Splay[] split(Splay root, int key) { if (root == NIL) { return new Splay[]{NIL, NIL}; } Splay p = root; while (root != NIL) { p = root; root.pushDown(); if (root.key > key) { root = root.left; } else { root = root.right; } } splay(p); if (p.key <= key) { return new Splay[]{p, splitRight(p)}; } else { return new Splay[]{splitLeft(p), p}; } } @Override public String toString() { StringBuilder builder = new StringBuilder().append(key).append(":"); toString(cloneTree(this), builder); return builder.toString(); } } public static class FastIO { public final StringBuilder cache = new StringBuilder(); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
13f45cea081de5419398dbb3950f8c01
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; import java.util.regex.*; public class Program { private static PrintWriter out; private static <T> void mprintln(T ... ar){ for(T i: ar) out.print(i + " "); out.println(); } public static void main(String[] args) throws FileNotFoundException{ // Input from file // File inputFile = new File("JavaFile.txt"); // File outputFile = new File("JavaOutputFile.txt"); // FileReader fileReader = new FileReader(inputFile); // Here it ends MyScanner sc = new MyScanner(); // MyScanner sc = new MyScanner(fileReader); out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console // out = new PrintWriter(new PrintStream(outputFile)); // Output to file getAns(sc); out.close(); } // Global Variables static HashMap<Long, Integer> map; private static void getAns(MyScanner sc){ int t = sc.ni(); testcase: while(t-- > 0){ int n = sc.ni(), m = sc.ni(); char[][] ar = new char[n][m]; for(int i = 0; i < n; i++) ar[i] = sc.nn().toCharArray(); HashMap<Character, ArrayList<int[]>> map = new HashMap(); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++){ map.putIfAbsent(ar[i][j], new ArrayList()); map.get(ar[i][j]).add(new int[]{i, j}); } ArrayList<int[]> ans = new ArrayList(); char[][] br = new char[n][m]; for(int i = 0; i < n; i++) Arrays.fill(br[i], '.'); int[][] pos = new int[26][4]; char ch = 'a', last = 'a' - 1; while(ch <= 'z'){ if(!map.containsKey(ch)){ ++ch; continue; } if(!allIsWell(map.get(ch))){ out.println("NO"); continue testcase; } ArrayList<int[]> list = map.get(ch); int a = list.get(0)[0], b = list.get(0)[1], c = list.get(list.size() - 1)[0], d = list.get(list.size() - 1)[1]; pos[ch - 'a'][0] = a + 1; pos[ch - 'a'][1] = b + 1; pos[ch - 'a'][2] = c + 1; pos[ch - 'a'][3] = d + 1; fillChar(br, ch, a, b, c, d); last = ch; ++ch; } // out.println(Arrays.deepToString(br)); for(int i = 0; i < n; i++){ if(!Arrays.equals(ar[i], br[i])){ out.println("NO"); continue testcase; } } out.println("YES"); out.println(last - 'a' + 1); int index = last - 'a' - 1; while(index >= 0){ if(pos[index][0] == 0){ pos[index][0] = pos[index + 1][0]; pos[index][1] = pos[index + 1][1]; pos[index][2] = pos[index + 1][2]; pos[index][3] = pos[index + 1][3]; } --index; } for(int i = 0; i <= last - 'a'; i++) out.println(pos[i][0] + " " + pos[i][1] + " " + pos[i][2] + " " + pos[i][3]); } } private static void fillChar(char[][] br, char ch, int a, int b, int c, int d){ if(a == c) for(int i = b; i <= d; i++) br[a][i] = ch; if(b == d) for(int i = a; i <= c; i++) br[i][b] = ch; } private static boolean allIsWell(ArrayList<int[]> list) { if(list.size() == 1) return true; boolean hor = true, ver = true; for(int i = 1; i < list.size() - 1; i++){ hor &= list.get(i - 1)[0] == list.get(i)[0]; ver &= list.get(i - 1)[1] == list.get(i)[1]; } return ver | hor; } static class MyScanner{ BufferedReader br; StringTokenizer st; MyScanner(FileReader fileReader){ br = new BufferedReader(fileReader); } MyScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } String nn(){ while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String ans = ""; try { ans = br.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return ans; } char nc(){ return nn().charAt(0); } int ni(){ return Integer.parseInt(nn()); } long nl(){ return Long.parseLong(nn()); } double nd(){ return Double.parseDouble(nn()); } int[] niArr0(int n){ int[] ar = new int[n]; for(int i = 0; i < n; i++) ar[i] = ni(); return ar; } int[] niArr1(int n){ int[] ar = new int[n + 1]; for(int i = 1; i <= n; i++) ar[i] = ni(); return ar; } long[] nlArr0(int n){ long[] ar = new long[n]; for(int i = 0; i < n; i++) ar[i] = nl(); return ar; } long[] nlArr1(int n){ long[] ar = new long[n + 1]; for(int i = 1; i <= n; i++) ar[i] = nl(); return ar; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
3e8a726decb0d859a4a87d6e4847d9c9
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.Objects; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); EPolycarpAndSnakes solver = new EPolycarpAndSnakes(); solver.solve(1, in, out); out.close(); } static class EPolycarpAndSnakes { public void solve(int testNumber, LightScanner in, LightWriter out) { out.setBoolLabel(LightWriter.BoolLabel.YES_NO_ALL_UP); int testCases = in.ints(); char[][] board = new char[2000][]; int[] maxX = new int[26], minX = new int[26]; int[] maxY = new int[26], minY = new int[26]; loop: for (int testCase = 0; testCase < testCases; testCase++) { int h = in.ints(), w = in.ints(); for (int i = 0; i < h; i++) { board[i] = in.string().toCharArray(); } Arrays.fill(maxX, -1); Arrays.fill(maxY, -1); Arrays.fill(minX, Integer.MAX_VALUE); Arrays.fill(minY, Integer.MAX_VALUE); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { char c = board[i][j]; if (c == '.') continue; maxX[c - 'a'] = Math.max(maxX[c - 'a'], j); maxY[c - 'a'] = Math.max(maxY[c - 'a'], i); minX[c - 'a'] = Math.min(minX[c - 'a'], j); minY[c - 'a'] = Math.min(minY[c - 'a'], i); } } int maxChar = -1, tmpX = -1, tmpY = -1; for (int i = 0; i < 26; i++) { if (maxX[i] == -1) continue; maxChar = Math.max(maxChar, i); tmpX = minX[i]; tmpY = minY[i]; if (maxX[i] == minX[i]) { int x = maxX[i]; for (int j = minY[i]; j <= maxY[i]; j++) { if (board[j][x] == '.' || board[j][x] - 'a' < i) { out.noln(); continue loop; } } } else if (maxY[i] == minY[i]) { int y = maxY[i]; for (int j = minX[i]; j <= maxX[i]; j++) { if (board[y][j] == '.' || board[y][j] - 'a' < i) { out.noln(); continue loop; } } } else { out.noln(); continue loop; } } maxChar++; /*for (int i = 1; i < h - 1; i++) { for (int j = 0; j < w; j++) { char c = board[i][j]; if (c == '.') continue; if (board[i - 1][j] == '.' || board[i + 1][j] == '.') continue; if (board[i - 1][j] != board[i + 1][j]) continue; if (board[i - 1][j] <= c) continue; //System.out.println("VERTICAL MISOVERWRITE"); out.noln(); continue loop; } } for (int i = 0; i < h; i++) { for (int j = 1; j < w - 1; j++) { char c = board[i][j]; if (c == '.') continue; if (board[i][j - 1] == '.' || board[i][j + 1] == '.') continue; if (board[i][j - 1] != board[i][j + 1]) continue; if (board[i][j - 1] <= c) continue; //System.out.println("HORIZONTAL MISOVERWRITE"); out.noln(); continue loop; } }*/ out.yesln().ans(maxChar).ln(); for (int i = 0; i < maxChar; i++) { if (maxX[i] == -1) { out.ans(tmpY + 1).ans(tmpX + 1).ans(tmpY + 1).ans(tmpX + 1).ln(); } else { out.ans(minY[i] + 1).ans(minX[i] + 1).ans(maxY[i] + 1).ans(maxX[i] + 1).ln(); } } } } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; private LightWriter.BoolLabel boolLabel = LightWriter.BoolLabel.YES_NO_FIRST_UP; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public void setBoolLabel(LightWriter.BoolLabel label) { this.boolLabel = Objects.requireNonNull(label); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ans(boolean b) { return ans(boolLabel.transfer(b)); } public LightWriter yesln() { return ans(true).ln(); } public LightWriter noln() { return ans(false).ln(); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } public enum BoolLabel { YES_NO_FIRST_UP("Yes", "No"), YES_NO_ALL_UP("YES", "NO"), YES_NO_ALL_DOWN("yes", "no"), Y_N_ALL_UP("Y", "N"), POSSIBLE_IMPOSSIBLE_FIRST_UP("Possible", "Impossible"), POSSIBLE_IMPOSSIBLE_ALL_UP("POSSIBLE", "IMPOSSIBLE"), POSSIBLE_IMPOSSIBLE_ALL_DOWN("possible", "impossible"), FIRST_SECOND_FIRST_UP("First", "Second"), FIRST_SECOND_ALL_UP("FIRST", "SECOND"), FIRST_SECOND_ALL_DOWN("first", "second"), ALICE_BOB_FIRST_UP("Alice", "Bob"), ALICE_BOB_ALL_UP("ALICE", "BOB"), ALICE_BOB_ALL_DOWN("alice", "bob"), ; private final String positive; private final String negative; BoolLabel(String positive, String negative) { this.positive = positive; this.negative = negative; } private String transfer(boolean f) { return f ? positive : negative; } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
87f0ac70c049b57506a1d83aa202c545
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C1185E { private static BufferedReader in; private static BufferedWriter out; private static List<Integer>[] list; private static int[] arr; private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static boolean[] used; public static void main(String[] args) throws IOException { open(); int t = readInt(); while (t-- > 0) { int[] nm = readInts(); int n = nm[0]; int m = nm[1]; char[][] tab = new char[n][m]; for (int i = 0; i < n; i++) { tab[i] = readString().toCharArray(); } int[] top = new int[26]; int[] bottom = new int[26]; int[] left = new int[26]; int[] right = new int[26]; Arrays.fill(top, -1); Arrays.fill(bottom, 3000); Arrays.fill(left, 3000); Arrays.fill(right, -1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char c = tab[i][j]; if (c != '.') { int v = c - 'a'; top[v] = Math.max(top[v], i); bottom[v] = Math.min(bottom[v], i); left[v] = Math.min(left[v], j); right[v] = Math.max(right[v], j); } } } boolean yes = true; for (int i = 0; i < 26; i++) { if (top[i] != -1 && top[i] != bottom[i] && left[i] != right[i]) { yes = false; break; } else { for (int x = bottom[i]; x <= top[i]; x++) { for (int y = left[i]; y <= right[i]; y++) { if (tab[x][y] == '.' || tab[x][y] - 'a' < i) { yes = false; break; } } if (!yes) { break; } } } } if (yes) { out.write("YES\n"); List<int[]> list = new ArrayList<>(); int prev = -1; for (int i = 25; i >= 0; i--) { if (top[i] == -1) { if (prev != -1) { int[] p = list.get(list.size() - 1); int[] np = new int[4]; for (int j = 0; j < 4; j++) { np[j] = p[j]; } list.add(np); prev = i; } } else { int[] p = new int[4]; p[0] = top[i] + 1; p[1] = left[i] + 1; p[2] = bottom[i] + 1; p[3] = right[i] + 1; list.add(p); prev = i; } } out.write(list.size() + "\n"); for (int i = list.size() - 1; i >= 0; i--) { int[] p = list.get(i); for (int j = 0; j < 4; j++) { out.write(p[j] + " "); } out.write("\n"); } } else { out.write("NO\n"); } } close(); } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException { List<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int[] e = readInts(); list[e[0]].add(e[1]); list[e[1]].add(e[0]); } return list; } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
44dc63c38173cb5cc85b4d85235653f4
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class TaskE { public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int m = in.nextInt(); char[][] s = getCharArr(in, n, m); int[][] r = solve(n, m, s); if (r != null) { System.out.println("YES"); System.out.println(r.length); for (int j = 0; j < r.length; j++) { System.out.println(str(r[j])); } } else { System.out.println("NO"); } } in.close(); } private static int[][] solve(int n, int m, char[][] s) { Map<Character, int[][]> index = new HashMap<>(); int min = 'z' + 1; int max = 'a' - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char c = s[i][j]; if (c != '.') { if (!index.containsKey(c)) { max = Math.max(max, c); min = Math.min(min, c); index.put(c, new int[][] { new int[] { i + 1, j + 1 }, new int[] { i + 1, j + 1 } }); } int[][] range = index.get(c); if (range[0][0] != i + 1 && range[0][1] != j + 1) { return null; } if ((range[0][0] != i + 1 || range[1][0] != i + 1) && (range[0][1] != j + 1 || range[1][1] != j + 1)) { return null; } range[1] = new int[] { i + 1, j + 1 }; } } } int[][] r = new int[max - 'a' + 1][]; if (max < 'a') { return new int[0][]; } int[] maxStart = index.get((char) max)[0]; for (int i = 'a'; i <= max; i++) { char c = (char) i; if (index.containsKey(c)) { int[][] range = index.get(c); if (range[0][0] == range[1][0]) { for (int j = range[0][1]; j <= range[1][1]; j++) { if (s[range[0][0] - 1][j - 1] < c) { return null; } } } else { for (int j = range[0][0]; j <= range[1][0]; j++) { if (s[j - 1][range[0][1] - 1] < c) { return null; } } } r[i - 'a'] = new int[] { range[0][0], range[0][1], range[1][0], range[1][1] }; } else { r[i - 'a'] = new int[] { maxStart[0], maxStart[1], maxStart[0], maxStart[1] }; } } return r; } static long mod = 1000000007; static long add(long a, long b) { long r = a + b; if (r < 0) { r += mod; } return r % mod; } static long mul(long a, long b) { return (a * b) % mod; } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static String str(List<Integer> a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.size(); i++) { sb.append(a.get(i) + " "); } return sb.toString(); } static String str(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { sb.append(a[i] + " "); } return sb.toString(); } static int[] getIntArr(Scanner in, int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = in.nextInt(); } return arr; } static int[][] getIntArr(Scanner in, int row, int col) { int[][] arr = new int[row][]; for (int i = 0; i < row; i++) { arr[i] = getIntArr(in, col); } return arr; } static long[] getLongArr(Scanner in, int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = in.nextLong(); } return arr; } static long[][] getLongArr(Scanner in, int row, int col) { long[][] arr = new long[row][]; for (int i = 0; i < row; i++) { arr[i] = getLongArr(in, col); } return arr; } static char[] getCharArr(Scanner in, int size) { char[] arr = in.next().toCharArray(); return arr; } static char[][] getCharArr(Scanner in, int row, int col) { char[][] arr = new char[row][]; for (int i = 0; i < row; i++) { arr[i] = getCharArr(in, col); } return arr; } static String[] getStringArr(Scanner in, int size) { String[] arr = new String[size]; for (int i = 0; i < size; i++) { arr[i] = in.next(); } return arr; } static Map<Integer, List<Integer>> getEdges(Scanner in, int size, boolean directed) { Map<Integer, List<Integer>> edges = new HashMap<>(); for (int i = 0; i < size; i++) { int from = in.nextInt(); int to = in.nextInt(); if (!edges.containsKey(from)) { edges.put(from, new ArrayList<Integer>()); } edges.get(from).add(to); if (!directed) { if (!edges.containsKey(to)) { edges.put(to, new ArrayList<Integer>()); } edges.get(to).add(from); } } return edges; } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
d4972b4ef6ffb836d36eb35627590681
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner in =new Scanner(System.in); int t= in.nextInt(); outer: while(t-->0){ int n =in.nextInt(); int m = in.nextInt(); char c[][] = new char[n][m]; for(int i=0;i<n;i++){ c[i] = in.next().toCharArray(); } Data d[][] = new Data[26][Math.max(n,m)]; int indexs[] = new int[26]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(c[i][j]!='.'){ if(indexs[c[i][j]-'a']==d[0].length){ System.out.println("NO"); continue outer; } d[c[i][j]-'a'][indexs[c[i][j]-'a']++] = new Data(i,j); } } } for(int i=0;i<26;i++){ boolean p = true; for(int j=0;j<indexs[i];j++){ p &= d[i][0].a==d[i][j].a; } boolean q = true; for(int j=0;j<indexs[i];j++){ q &= d[i][0].b==d[i][j].b; } if(!(p||q)){ System.out.println("NO"); continue outer; } } String s[] = new String[26]; int count = 0; for(int j=26-1;j>=0;j--){ if(indexs[j]==0){ if(j<25){ if(s[j+1] != null){ s[j] = s[j+1]; count++; } } } else{ int x1 = Integer.MAX_VALUE; int y1 = Integer.MAX_VALUE; int x2 = Integer.MIN_VALUE; int y2 = Integer.MIN_VALUE; for(int i=0;i<indexs[j];i++){ Data dd = d[j][i]; x1 = Math.min(x1, dd.a); y1 = Math.min(y1, dd.b); x2 = Math.max(x2, dd.a); y2 = Math.max(y2, dd.b); } for(int i=x1;i<=x2;i++){ for(int k=y1;k<=y2;k++){ if(c[i][k] == '.'){ System.out.println("NO"); continue outer; } else if(c[i][k] == j+'a' || c[i][k] == '?'){ } else{ System.out.println("NO"); continue outer; } c[i][k] = '?'; } } x1++; x2++; y1++; y2++; count++; s[j] = x1+" "+y1+" "+x2+" "+y2; } } System.out.println("YES"); System.out.println(count); for(int i=0;i<count;i++){ System.out.println(s[i]); } } } static class Data{ int a, b; public Data(int a,int b){ this.a = a; this.b = b; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
d10597bc809f45781649abe1abb2e64f
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; public class D{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int q=0;q<t;q++){ ans = new ArrayList<>(); String s[] = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); char arr[][] = new char[n][m]; for(int i=0;i<n;i++){ arr[i] = br.readLine().toCharArray(); } boolean flag = false; quadruple first = null; outer:for(int l=25;l>=0;l--){ char c = (char)(l+'a'); boolean removed=false; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(arr[i][j]==c){ if(first==null){ first = new quadruple(i,j,i,j); } if(removed){/* System.out.println(c+" "+i+" "+j); for(int u=0;u<n;u++) System.out.println(Arrays.toString(arr[u]));*/ System.out.println("NO"); flag = true; break outer; } else{/* System.out.println(c+" "+i+" "+j); for(int u=0;u<n;u++) System.out.println(Arrays.toString(arr[u]));*/ remove(arr,i,j,c,n,m); removed = true; } } } } if(first!=null && !removed){ ans.add(first); } } if(!flag){ System.out.println("YES"); System.out.println(ans.size()); for(int i=ans.size()-1;i>=0;i--){ System.out.println((ans.get(i).x1+1)+" "+(ans.get(i).y1+1)+" "+(ans.get(i).x2+1)+" "+(ans.get(i).y2+1)); } } } } static class quadruple{ int x1,x2,y1,y2; quadruple(int a,int b,int c,int d){ x1=a; y1=b; x2=c; y2=d; } } static ArrayList<quadruple> ans = new ArrayList<>(); public static void remove(char arr[][],int x,int y,char c,int n,int m){ int i=y; int count=0; for(i=y;i<m;i++){ if(arr[x][i]==c || arr[x][i]=='-'){ if(arr[x][i]==c) count++; arr[x][i]='-'; } else{ if(count>=2){ ans.add(new quadruple(x,y,x,i-1)); return; } break; } } if(count>1 && i==m){ ans.add(new quadruple(x,y,x,i-1)); return; } for(i=x;i<n;i++){ if(arr[i][y]==c || arr[i][y]=='-'){ arr[i][y]='-'; } else{ ans.add(new quadruple(x,y,i-1,y)); return; } } if(i==n){ ans.add(new quadruple(x,y,i-1,y)); return; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
594a9acdac75e0bea6417fa368f27763
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.Scanner; public class Main { private static boolean color(int x1 , int y1 , int x2 , int y2 , char ch) { for (int i = x1;i <= x2;i ++) { for (int j = y1;j <= y2;j ++) { if (matrix[i][j] == '*' || matrix[i][j] == ch) { continue; } else { return false; } } } for (int i = x1;i <= x2;i ++) { for (int j = y1;j <= y2;j ++) { matrix[i][j] = '*'; } } return true; } private static char[][] matrix = new char[2010][2010]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i , j , t = scan.nextInt(); while (t > 0) { int[] minX = new int[26]; int[] maxX = new int[26]; int[] minY = new int[26]; int[] maxY = new int[26]; for (i = 0;i < 26;i ++) { minX[i] = Integer.MAX_VALUE; maxX[i] = Integer.MIN_VALUE; minY[i] = Integer.MAX_VALUE; maxY[i] = Integer.MIN_VALUE; } int n , m; n = scan.nextInt(); m = scan.nextInt(); for (i = 0;i < n;i ++) { String string = scan.next(); for (j = 0;j < m;j ++) { matrix[i][j] = string.charAt(j); if (matrix[i][j] != '.') { int index = matrix[i][j] - 'a'; if (i < minX[index]) { minX[index] = i; } if (i > maxX[index]) { maxX[index] = i; } if (j < minY[index]) { minY[index] = j; } if (j > maxY[index]) { maxY[index] = j; } } } } boolean result = true; for (i = 25;i >= 0;i --) { if (minX[i] != Integer.MAX_VALUE) { if (minX[i] != maxX[i] && minY[i] != maxY[i]) { result = false; break; } else { if (!color(minX[i] , minY[i] , maxX[i] , maxY[i] , (char) (i + 'a'))) { result = false; break; } } } } for (i = 0;i < n;i ++) { for (j = 0;j < m;j ++) { if (matrix[i][j] >= 'a' && matrix[i][j] <= 'z') { result = false; } } } if (result) { System.out.println("YES"); int lastIndex = - 1; for (i = 0;i < 26;i ++) { if (minX[i] != Integer.MAX_VALUE) { lastIndex = i; } } System.out.println(lastIndex + 1); for (i = 0;i <= lastIndex;i ++) { if (minX[i] != Integer.MAX_VALUE) { System.out.println(String.format("%d %d %d %d" , minX[i] + 1 , minY[i] + 1 , maxX[i] + 1 , maxY[i] + 1)); } else { System.out.println(String.format("%d %d %d %d" , minX[lastIndex] + 1 , minY[lastIndex] + 1 , minX[lastIndex] + 1 , minY[lastIndex] + 1)); } } } else { System.out.println("NO"); } t --; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
e8180c2da232578d39d5d09660b7d0d3
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Comparator.comparingLong; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), m = in.nextInt(); int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { char[] s = in.next().toCharArray(); for (int j = 0; j < m; j++) map[i][j] = s[j] == '.' ? -1 : s[j] - 'a'; } int inf = (int) 1e9; int[] maxI = new int[26], minI = new int[26], maxJ = new int[26], minJ = new int[26]; fill(maxI, -inf); fill(maxJ, -inf); fill(minI, inf); fill(minJ, inf); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] != -1) { maxI[map[i][j]] = max(maxI[map[i][j]], i); maxJ[map[i][j]] = max(maxJ[map[i][j]], j); minI[map[i][j]] = min(minI[map[i][j]], i); minJ[map[i][j]] = min(minJ[map[i][j]], j); } } } int k = 26; while (k > 0 && maxI[k - 1] < minI[k - 1]) k--; for (int i = 0; i < k; i++) { if (maxI[i] > minI[i] && maxJ[i] > minJ[i]) { out.println("NO"); return; } } for (int i = k - 2; i >= 0; i--) { if (maxI[i] < minI[i]) { maxI[i] = maxI[i + 1]; maxJ[i] = maxJ[i + 1]; minI[i] = minI[i + 1]; minJ[i] = minJ[i + 1]; } } int[][] paint = new int[n][m]; for (int i = 0; i < n; i++) fill(paint[i], -1); for (int c = 0; c < k; c++) for (int i = minI[c]; i <= maxI[c]; i++) for (int j = minJ[c]; j <= maxJ[c]; j++) paint[i][j] = c; boolean ok = true; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ok &= paint[i][j] == map[i][j]; out.println(ok ? "YES" : "NO"); if (ok) { out.println(k); for (int i = 0; i < k; i++) out.println((minI[i] + 1) + " " + (minJ[i] + 1) + " " + (maxI[i] + 1) + " " + (maxJ[i] + 1)); } } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); for (int t = in.nextInt(); t-- > 0; ) solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
2111059fc36bda60e501b86c05615913
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Rough { static Scanner sc = new Scanner(System.in); static StringBuilder sb = new StringBuilder(); static PrintWriter pw = new PrintWriter(System.out, true); public static void main(String[] args) { //code goes here int t = sc.nextInt(); while(t-- >0) { int n = sc.nextInt(),m = sc.nextInt(); char arr[][]= new char[n][]; for(int i =0;i<n;i++) arr[i]= sc.next().toCharArray(); ArrayList<Pair> alpha[] = new ArrayList[26]; for(int i=0;i<26;i++) alpha[i]=new ArrayList<Pair>(); for(int i =0;i<n;i++) for(int j =0;j<m;j++) { if(arr[i][j]!='.') { alpha[arr[i][j] - 'a'].add(new Pair(i, j)); } } boolean bool = true; int rep[]= new int[26]; for(int i =25;i>=0;i--) { if(alpha[i].size()>0) { int x =1,j=i; while(j>0 && alpha[j-1].size()==0) { j--; x++; } rep[i]=x; i=j; } } for(ArrayList<Pair> al : alpha) { if(al.size()<1) continue; Pair p = al.get(0),q =al.get(al.size()-1); if(p.i==q.i) { int cnt =0; for(int j = p.j;j<=q.j;j++) { if(!(arr[p.i][j]>=arr[p.i][p.j])){ bool = false; break; } if(arr[p.i][j]==arr[p.i][p.j]) cnt++; } if(cnt <al.size()) { bool = false; break; } } else if(p.j==q.j) { int cnt =0; for(int i = p.i;i<=q.i;i++) { if(!(arr[i][p.j]>=arr[p.i][p.j])){ bool = false; break; } if(arr[i][p.j]==arr[p.i][p.j]) cnt++; } if(cnt <al.size()) { bool = false; break; } } else { bool = false; break; } } if(bool) { sb.append("YES\n"); StringBuilder here = new StringBuilder(); int cnt =0; for(ArrayList<Pair> al : alpha) { if(al.size()>0) { Pair a = al.get(0),b = al.get(al.size()-1); while(rep[arr[a.i][a.j]-'a']-->0) { here.append((1 + a.i) + " " + (1 + a.j) + " " + (1 + b.i) + " " + (1 + b.j) + "\n"); cnt++; } } } sb.append(cnt+"\n"); sb.append(here); } else sb.append("NO\n"); } pw.println(sb); pw.flush(); pw.close(); } static class Pair { int i,j; Pair(int i,int j) { this.i=i; this.j=j; } public String tString() { return "{"+i+", "+j+"}"; } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
7a4507868841943f9d8114f3d8da1f11
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.util.*; import java.io.*; public class MainClass { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); StringBuilder stringBuilder = new StringBuilder(); while (t-- > 0) { String s1[] = in.readLine().split(" "); int n = Integer.parseInt(s1[0]); int m = Integer.parseInt(s1[1]); char[][] A = new char[n][m]; for (int i=0;i<n;i++) A[i] = in.readLine().toCharArray(); int[][] B = new int[n][m]; for (int i=0;i<n;i++) for (int j=0;j<m;j++) B[i][j] = (int)A[i][j]; ST ST = new ST(); ST.createST(B); ArrayList<Game>[] adj = new ArrayList[26]; for (int i=0;i<26;i++) adj[i] = new ArrayList<>(); for (int i=0;i<n;i++) for (int j=0;j<m;j++) { if (A[i][j] >= 'a' && A[i][j] <= 'z') { adj[A[i][j] - 'a'].add(new Game(i, j)); } } boolean ff = true; int count = 0; StringBuilder stringBuilder1 = new StringBuilder(); int lastMade = -1; for (int i=25;i>=0;i--) { if (adj[i].size() > 0) { lastMade = i; break; } } if (lastMade == -1) { stringBuilder.append("YES\n0\n"); continue; } int startRow = adj[lastMade].get(0).row + 1; int startCol = adj[lastMade].get(0).col + 1; int endRow = adj[lastMade].get(adj[lastMade].size() - 1).row + 1; int endCol = adj[lastMade].get(adj[lastMade].size() - 1).col + 1; for (int i=0;i<26;i++) { if (adj[i].size() == 0) { if (i < lastMade) { count++; stringBuilder1.append(startRow).append(" ").append(startCol).append(" ").append(endRow).append(" ").append(endCol).append("\n"); } continue; } if (adj[i].size() == 1) { count++; stringBuilder1.append(adj[i].get(0).row + 1).append(" ").append(adj[i].get(0).col + 1).append(" ").append(adj[i].get(0).row + 1).append(" ").append(adj[i].get(0).col + 1).append("\n"); continue; } Game first = adj[i].get(0); Game last = adj[i].get(adj[i].size() - 1); int min = 0; boolean ffRow = true; boolean ffCol = true; for (Game g: adj[i]) { if (g.row != adj[i].get(0).row) { ffRow = false; break; } } for (Game g: adj[i]) { if (g.col != adj[i].get(0).col) { ffCol = false; break; } } if (!ffRow && !ffCol) { ff = false; break; } if (first.row == last.row) { min = ST.queryST1(0, m - 1, first.col, last.col, 0, first.row); } else { min = ST.queryST2(0, n - 1, first.row, last.row, 0, first.col); } if (min < i + 97) { ff = false; break; } count++; stringBuilder1.append(first.row + 1).append(" ").append(first.col + 1).append(" ").append(last.row + 1).append(" ").append(last.col + 1).append("\n"); } if (!ff) stringBuilder.append("NO\n"); else { stringBuilder.append("YES\n"); stringBuilder.append(count).append("\n").append(stringBuilder1); } } System.out.println(stringBuilder); } } class Game { int row; int col; public Game(int row, int col) { this.row = row; this.col = col; } } class ST { int[][] st1; int[][] st2; public int nextPowerOfTwo(int num) { if (num == 0) return 1; if (num > 0 && (num & (num - 1)) == 0) return num; while ((num & (num - 1)) > 0) num = num & (num - 1); return num << 1; } public void createST(int[][] A) { int n = A.length; int m = A[0].length; int np2n = nextPowerOfTwo(n); int np2m = nextPowerOfTwo(m); st1 = new int[n][2 * np2m - 1]; st2 = new int[m][2 * np2n - 1]; for (int i=0;i<n;i++) constructST1(A, 0, m - 1, 0, i); for (int i=0;i<m;i++) constructST2(A, 0, n - 1, 0, i); } public void constructST1(int[][] A, int low, int high, int pos, int row) { if (low == high) { st1[row][pos] = A[row][low]; return; } int mid = (low + high) / 2; constructST1(A, low, mid, 2 * pos + 1, row); constructST1(A, mid + 1, high, 2 * pos + 2, row); st1[row][pos] = Math.min(st1[row][2 * pos + 1], st1[row][2 * pos + 2]); } public void constructST2(int[][] A, int low, int high, int pos, int col) { if (low == high) { st2[col][pos] = A[low][col]; return; } int mid = (low + high) / 2; constructST2(A, low, mid, 2 * pos + 1, col); constructST2(A, mid + 1, high, 2 * pos + 2, col); st2[col][pos] = Math.min(st2[col][2 * pos + 1], st2[col][2 * pos + 2]); } public int queryST1(int low, int high, int qlow, int qhigh, int pos, int row) { if (qlow <= low && qhigh >= high) { return st1[row][pos]; } if (qlow > high || qhigh < low) return Integer.MAX_VALUE; int mid = (low + high) / 2; return Math.min(queryST1(low, mid, qlow, qhigh, 2 * pos + 1, row), queryST1(mid + 1, high, qlow, qhigh, 2 * pos + 2, row)); } public int queryST2(int low, int high, int qlow, int qhigh, int pos, int col) { if (qlow <= low && qhigh >= high) { return st2[col][pos]; } if (qlow > high || qhigh < low) return Integer.MAX_VALUE; int mid = (low + high) / 2; return Math.min(queryST2(low, mid, qlow, qhigh, 2 * pos + 1, col), queryST2(mid + 1, high, qlow, qhigh, 2 * pos + 2, col)); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
882766f1f0ea652fc13f246b1378a669
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.BigInteger; import java.util.regex.*; public class Myclass { static char s[][]; static int n,m; static int start=0; static int end=0; static int cheak_row(int r,int c,char a) { int cnt=0; for(int i=r;i>=0;i--) { if(s[i][c]==a) { cnt++; s[i][c]='*'; } else if(s[i][c]=='*') continue; else { start=i; break; } } for(int i=r;i<n;i++) { if(s[i][c]==a) { cnt++; s[i][c]='*'; } else if(s[i][c]=='*') continue; else { end=i; break; } } return cnt; } static int cheak_col(int r,int c,char a) { int cnt=0; for(int i=c;i>=0;i--) { if(s[r][i]==a) { cnt++; s[r][i]='*'; } else if(s[r][i]=='*') continue; else { start=i; break; } } for(int i=c;i<m;i++) { if(s[r][i]==a) { cnt++; s[r][i]='*'; } else if(s[r][i]=='*') continue; else { end=i; break; } } return cnt; } public static void main(String[] args) throws IOException, ClassNotFoundException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int t=in.nextInt(); while(t-->0) { n=in.nextInt(); m=in.nextInt(); pair ans[]=new pair[26]; pair ans1[]=new pair[26]; s=new char [n][m]; for(int i=0;i<n;i++) { s[i]=in.nextLine().toCharArray(); } int maxi=-1; pair p[]=new pair[26]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(s[i][j]!='.') { maxi=Math.max(maxi, s[i][j]-'a'); p[s[i][j]-'a']=new pair(i,j); } } } for(int k=maxi;k>=0;k--) { if(p[k]==null) { ans[k]=new pair(ans[maxi].x,ans[maxi].y); ans1[k]=new pair(ans1[maxi].x,ans1[maxi].y); continue; } int x=p[k].x; int y=p[k].y; start=-1; end=n; int xx=cheak_row(x,y,(char)(k+'a')); ans[k]=new pair(start+2,y+1); ans1[k]=new pair(end,y+1); if(xx==1) { start=-1; end=m; int yy=cheak_col(x,y,(char)(k+'a')); ans[k]=new pair(x+1,start+2); ans1[k]=new pair(x+1,end); } } boolean chk=true; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(s[i][j]!='*' && s[i][j]!='.') chk=false; } } if(!chk) { pw.println("NO"); } else { pw.println("YES"); pw.println(maxi+1); for(int i=0;i<=maxi;i++) { pw.println(ans[i]+" "+ans1[i]); } } } pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000009; public static int d; public static int p; public static int q; public static long[] suffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static long GCD(long gcd,long diff) { if(diff==0) return gcd; else return GCD(diff,gcd%diff); } static class pair implements Comparable<pair> { Integer x; Integer y; pair(int a,int a2) { this.x=a; this.y=a2; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } } class Segment{ int seg[]; int a[]; Segment (int n,int b[]){ seg=new int[4*n]; a=new int[b.length]; a=b.clone(); } public Segment(int n) { seg=new int[4*n]; } public void build(int node,int start,int end) { if(start==end) { seg[node]=0; return ; } int mid=(start+end)/2; build(2*node+1,start,mid); build(2*node+2,mid+1,end); seg[node]=Math.min(seg[2*node+1],seg[2*node+2]); } public void update(int node,int start,int end,int id,int val) { if(start==end) { seg[node]=1; return; } int mid=(start+end)/2; if(id>=start && id<=mid) { update(2*node+1,start,mid,id,val); } else update(2*node+2,mid+1,end,id,val); seg[node]=seg[2*node+1]+seg[2*node+2]; } public int query(int node,int start,int end,int l,int r) { if(l>end || r<start) return 0; if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r)); } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
b8397c3720c6f315c8cfff7c78e970e2
train_001.jsonl
1560955500
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package coding; import java.util.*; /** * * @author Dell */ public class cdfrce1 { /** * */ public static char[][] table = new char[2100][2100]; public static int[][] cord = new int[27][4]; public static Map<Integer,Integer> count=new HashMap<>(); public static Scanner in = new Scanner(System.in); public static boolean testng = true; public static void check(int n, int m, int maxcc) { int maxc = maxcc; for (; maxc > 0; maxc--) { // char c=table[cord[maxc - 1][0]][cord[maxc - 1][1]]; /* System.out.println(cord[maxc - 1][0]); System.out.println(cord[maxc - 1][1]); System.out.println(cord[maxc - 1][2]); System.out.println(cord[maxc - 1][3]); */ if (cord[maxc - 1][3] == -1 && cord[maxc - 1][0] == -1) { cord[maxc - 1][2] = cord[maxcc - 1][2]; cord[maxc - 1][3] = cord[maxcc - 1][3]; cord[maxc - 1][0] = cord[maxcc - 1][0]; cord[maxc - 1][1] = cord[maxcc - 1][1]; } else if (cord[maxc - 1][0] == cord[maxc - 1][2]) { int t = cord[maxc - 1][0]; char c=table[cord[maxc - 1][0]][cord[maxc - 1][1]]; for (int i = cord[maxc - 1][3]; i > cord[maxc - 1][1]; i--) { // System.out.println("table 1 "+table[t][i]+" table 2 "+table[t][i-1]); //System.out.println(table[t][i] >= c); // System.out.println(table[t][i] <= 'z'); if(table[t][i]==c) {int temp=count.get(table[t][i] - 97); count.put(table[t][i] - 97, --temp); } if (!(table[t][i] >= c && table[t][i] <= 'z')) { testng = false; // System.out.println("hr 1"); break; } } if(count.get(maxc-1)>1) testng = false; } else if (cord[maxc - 1][1] == cord[maxc - 1][3]) { char c=table[cord[maxc - 1][0]][cord[maxc - 1][1]]; int t = cord[maxc - 1][1]; for (int i = cord[maxc - 1][2]; i > cord[maxc - 1][0]; i--) { //System.out.println("table 1 "+table[i][t]+" table 2 "+table[i - 1][t]); //System.out.println(table[i][t] >= c); // System.out.println(table[i][t] <= 'z'); if(table[i][t]==c) {int temp=count.get(table[i][t] - 97); count.put(table[i][t] - 97, --temp); } if (!(table[i][t] >= c && table[i][t] <= 'z')) { testng = false; // System.out.println("hr 2"); break; } } if(count.get(maxc-1)>1) testng = false; } else if (cord[maxc - 1][3] == -1 && cord[maxc - 1][0] != -1) { cord[maxc - 1][2] = cord[maxc - 1][0]; cord[maxc - 1][3] = cord[maxc - 1][1]; } else { testng = false; //System.out.println("hr 3"); break; } } } public static void main(String args[]) { int test = in.nextInt(); for (; test > 0; test--) { testng=true; int chars = 0;//= new int(); int n = in.nextInt(); int m = in.nextInt(); in.nextLine(); for (int i = 0; i < 26; i++) { cord[i][0] = -1; cord[i][1] = -1; cord[i][2] = -1; cord[i][3] = -1; count.put(i,0); } for (int i = 0; i < n; i++) { String s = in.nextLine(); for (int j = 0; j < m; j++) { table[i][j] = s.charAt(j); // System.out.println(table[i][j] - 96); if (table[i][j] <= 'z' && table[i][j] >= 'a') { int temp=count.get(table[i][j] - 97); count.put(table[i][j] - 97, ++temp); if (cord[table[i][j] - 97][0] == -1) { cord[table[i][j] - 97][0] = i; cord[table[i][j] - 97][1] = j; } else { cord[table[i][j] - 97][2] = i; cord[table[i][j] - 97][3] = j; } if (table[i][j] - 96 > chars) { chars = table[i][j] - 96; } } } } check(n,m,chars); if (testng) { System.out.println("YES"); if (chars == 0) { System.out.println(chars); } else { System.out.println(chars); for (int i = 0; i < chars; i++) { System.out.println((cord[i][0]+1) + " " + (cord[i][1]+1 )+ " " + (cord[i][2]+1) + " " + (cord[i][3]+1)); } } } else { System.out.println("NO"); } // System.out.println(chars); } } }
Java
["1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..", "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc"]
4 seconds
["YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5", "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2"]
null
Java 8
standard input
[ "implementation", "brute force" ]
f34d21b9568c758cacc1d00af1316c86
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$)Β β€” length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.
2,000
Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$)Β β€” number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$Β β€” coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.
standard output
PASSED
9bbd150b8cac63c0396d4bff7f762678
train_001.jsonl
1438273200
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as . Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.Find the matching between students and pseudonyms with the maximum quality.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.StringTokenizer; public class CodeforceSol11a { static FastScanner in; static PrintWriter out; public static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(InputStream in){ br = new BufferedReader(new InputStreamReader(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()); } } /* public static class Trie{ private class Node{ public char value; public HashMap<Character,Node> children; public boolean bIsEnd; public Node(char ch){ value = ch; children = new HashMap<Character,Node>(); bIsEnd = false; } } private Node root; public Trie(){ root = new Node((char) 0); } public void addWord(String word){ int length = word.length(); Node cur = root; for(int level = 0; level < length; level++) { HashMap<Character,Node> child = cur.children; char ch = word.charAt(level); if(child.containsKey(ch)) cur = child.get(ch); else { child.put(ch, new Node(ch) ); cur = child.get(ch); } } cur.bIsEnd = true; } public String getMatchPrefix(String input) { String result = ""; int length = input.length(); Node cur = root; int level, prevMatch = 0; for( level = 0 ; level < length; level++ ){ char ch = input.charAt(level); HashMap<Character,Node> child = cur.children; if(child.containsKey(ch)){ result += ch; cur = child.get(ch); prevMatch++; if(cur.bIsEnd) prevMatch = level + 1; } else break; } if( !cur.bIsEnd ) return result.substring(0, prevMatch); else return result; } }*/ public static void main(String[] args) { // TODO Auto-generated method stub in = new FastScanner(System.in); out = new PrintWriter(System.out); Task work = new Task(); work.solve(0, in, out); /* Trie tree = new Trie(); ArrayList<String> students = new ArrayList<String>(); ArrayList<String> pseudo = new ArrayList<String>(); int num_students = in.nextInt(); for(int no = 0; no < num_students; no++){ String name = in.next(); students.add(name); } String[] pseudoIndx = new String[num_students]; for(int no2 = 0; no2 < num_students; no2++){ String word = in.next(); pseudo.add(word); pseudoIndx[no2] = word; tree.addWord(word); } HashMap<Integer, Integer> result = new HashMap<Integer, Integer>(); ArrayList<String> nameprefix = new ArrayList<String>(); int score = 0; for(int st = 0; st < num_students; st++){ String prefix = tree.getMatchPrefix(students.get(st)); nameprefix.add(prefix); } boolean[] used = new boolean[num_students]; boolean[] usedV = new boolean[num_students]; ArrayList<Integer> left = new ArrayList<Integer>(); while(result.size() != num_students){ int maxidx = 0; int maxval = -1; for(int potidx = 0; potidx < num_students; potidx++){ if(nameprefix.get(potidx).length() > maxval && used[potidx] == false){ maxval = nameprefix.get(potidx).length(); maxidx = potidx; } } boolean found = false; int idx = 0; for(int i = 0; i < num_students; i++){ if(pseudo.get(i).startsWith(nameprefix.get(maxidx)) && usedV[i] == false){ score += maxval; idx = i; found = true; usedV[i] = true; break; } if(usedV[i] == false){ idx = i; } } if(found){ used[maxidx] = true; result.put(maxidx, idx); } else{ used[maxidx] = true; left.add(maxidx); result.put(maxidx, idx); } } for(int idx1 : left){ for(int idx2 = 0; idx2 < num_students; idx2++){ if(!usedV[idx2]){ result.put(idx1, idx2); used[idx1] = true; usedV[idx2] = true; break; } } } System.out.println(score); int s = 0; for(int v: result.keySet()){ System.out.println(Integer.toString(v+1) + " " + Integer.toString(result.get(v)+1)); s++; } */ out.close(); } static class Task { int sz = 1; final int maxSz = 800_100; int[][] links = new int[maxSz][26]; IntArrayList[] name = new IntArrayList[maxSz]; IntArrayList[] hob = new IntArrayList[maxSz]; int[] depth = new int[maxSz]; IntArrayList order = new IntArrayList(); long ans = 0; StringBuilder answer = new StringBuilder(); { ArrayUtils.fill(links, -1); } public void add(CharSequence word, boolean isName, int id) { int current = 0; int length = word.length(); for (int i = 0; i < length; i++) { int letter = word.charAt(i) - 'a'; if (links[current][letter] == -1) links[current][letter] = sz++; current = links[current][letter]; depth[current] = i + 1; } if (name[current] == null) name[current] = new IntArrayList(1); if (hob[current] == null) hob[current] = new IntArrayList(1); if (isName) name[current].add(id); else hob[current].add(id); } void dfs(int v) { for (int ch = 0; ch < 26; ++ch) { int link = links[v][ch]; if (link == -1) continue; dfs(link); } order.add(v); } private void upd(int v) { for (int ch = 0; ch < 26; ++ch) { int link = links[v][ch]; if (link == -1) continue; name[v] = f(name[v], name[link]); hob[v] = f(hob[v], hob[link]); } while (0 < hob[v].size() && 0 < name[v].size()) { answer.append(name[v].popBack()).append(" ").append(hob[v].popBack()).append("\n"); ans += depth[v]; } } private IntArrayList f(IntArrayList a, IntArrayList b) { if (a == null) return b; if (b == null) return a; if (a.size() < b.size()) return f(b, a); for (int i = 0; i < b.size(); i++) { a.add(b.get(i)); } return a; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); for (int i = 0; i < n; i++) { add(in.next(), true, i + 1); } for (int i = 0; i < n; i++) { add(in.next(), false, i + 1); } dfs(0); for (int i = 0; i < order.size(); ++i) upd(order.get(i)); out.println(ans); out.println(answer); out.flush(); } static abstract class IntList extends IntCollection implements Comparable<IntList> { public abstract int get(int index); public IntIterator iterator() { return new IntIterator() { private int size = size(); private int index = 0; public int value() throws NoSuchElementException { if (!isValid()) throw new NoSuchElementException(); return get(index); } public void advance() throws NoSuchElementException { if (!isValid()) throw new NoSuchElementException(); index++; } public boolean isValid() { return index < size; } }; } public int hashCode() { int hashCode = 1; for (IntIterator i = iterator(); i.isValid(); i.advance()) hashCode = 31 * hashCode + i.value(); return hashCode; } public boolean equals(Object obj) { if (!(obj instanceof IntList)) return false; IntList list = (IntList) obj; if (list.size() != size()) return false; IntIterator i = iterator(); IntIterator j = list.iterator(); while (i.isValid()) { if (i.value() != j.value()) return false; i.advance(); j.advance(); } return true; } public int compareTo(IntList o) { IntIterator i = iterator(); IntIterator j = o.iterator(); while (true) { if (i.isValid()) { if (j.isValid()) { if (i.value() != j.value()) { if (i.value() < j.value()) return -1; else return 1; } } else return 1; } else { if (j.isValid()) return -1; else return 0; } i.advance(); j.advance(); } } } static abstract class IntCollection { public abstract IntIterator iterator(); public abstract int size(); public abstract void add(int value); public void addAll(IntCollection values) { for (IntIterator it = values.iterator(); it.isValid(); it.advance()) { add(it.value()); } } } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) Arrays.fill(row, value); } } static class IntArrayList extends IntList { private int[] array; private int size; public IntArrayList() { this(10); } public IntArrayList(int capacity) { array = new int[capacity]; } public IntArrayList(IntList list) { this(list.size()); addAll(list); } public int get(int index) { if (index >= size) throw new IndexOutOfBoundsException(); return array[index]; } public int size() { return size; } public void add(int value) { ensureCapacity(size + 1); array[size++] = value; } public void ensureCapacity(int newCapacity) { if (newCapacity > array.length) { int[] newArray = new int[Math.max(newCapacity, array.length << 1)]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } } public int popBack() { return array[--size]; } } static interface IntIterator { public int value(); public void advance(); public boolean isValid(); } } }
Java
["5\ngennady\ngalya\nboris\nbill\ntoshik\nbilbo\ntorin\ngendalf\nsmaug\ngaladriel"]
2 seconds
["11\n4 1\n2 5\n1 3\n5 2\n3 4"]
NoteThe first test from the statement the match looks as follows: bill  →  bilbo (lcp = 3) galya  →  galadriel (lcp = 3) gennady  →  gendalf (lcp = 3) toshik  →  torin (lcp = 2) boris  →  smaug (lcp = 0)
Java 8
standard input
[ "dfs and similar", "trees", "strings" ]
c151fe26b4152474c78fd71c7ab49c88
The first line contains number n (1 ≀ n ≀ 100 000) β€” the number of students in the summer school. Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating. The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating. The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
2,300
In the first line print the maximum possible quality of matching pseudonyms to students. In the next n lines describe the optimal matching. Each line must have the form a b (1 ≀ a, b ≀ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input. The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
standard output