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
23664df5cc471ff9ef1627663d749f71
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class Towers { public static int min ( int a, int b) { return ( a <= b ) ? a : b; } public static void main ( String[] args ) { Scanner input = new Scanner(System.in); int n; n = input.nextInt(); String[] a = new String[n]; String[] b = new String[n]; int s1 = 0; int s2 = 0; int m1 = 0; int m2 = 0; int l1 = 0; int l2 = 0; int xs1 = 0; int xs2 = 0; int xxs1 = 0; int xxs2 = 0; int xxxs1 = 0; int xxxs2 = 0; int xl1 = 0; int xl2 = 0; int xxl1 = 0; int xxl2 = 0; int xxxl1 = 0; int xxxl2 = 0; for ( int i =0 ; i < n; ++i ) { a[i] = input.next(); switch(a[i]) { case "S" : {s1++; break; } case "M" : {m1++; break; } case "L" : {l1++; break; } case "XS" : {xs1++; break; } case "XXS" : {xxs1++; break; } case "XXXS" : {xxxs1++; break; } case "XL" : {xl1++; break; } case "XXL" : {xxl1++; break; } case "XXXL" : {xxxl1++; break; } } } for ( int i =0 ; i < n; ++i ) { b[i] = input.next(); switch(b[i]) { case "S" : {s2++; break; } case "M" : {m2++; break; } case "L" : {l2++; break; } case "XS" : {xs2++; break; } case "XXS" : {xxs2++; break; } case "XXXS" : {xxxs2++; break; } case "XL" : {xl2++; break; } case "XXL" : {xxl2++; break; } case "XXXL" : {xxxl2++; break; } } } int sum = min(s1,s2) + min(m1,m2) + min(l1,l2) + min(xs1,xs2) + min(xxs1,xxs2) + min (xxxs1,xxxs2) + min(xl1,xl2) + min(xxl1,xxl2) + min(xxxl1,xxxl2); System.out.println(n - sum); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
2e2fed0296cc4f10afbb374fffe9695a
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Puskar */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = in.nextString(); HashMap<String, Integer> hm1 = new HashMap<>(); hm1.put("XXXS",0); hm1.put("XXS",0); hm1.put("XS",0); hm1.put("S",0); hm1.put("XXXL",0); hm1.put("XXL",0); hm1.put("XL",0); hm1.put("L",0); hm1.put("M",0); for (int i = 0; i < n; i++) { hm1.put(a[i], hm1.get(a[i]) + 1); } int c = 0; for (int i = 0; i < n; i++) { a[0] = in.nextString(); if(hm1.get(a[0]) > 0) hm1.put(a[0], hm1.get(a[0]) - 1); else c++; } out.println(c); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
3f73712e2c594fd6007262b63e6b20f9
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; public class Main { static long mod=(long)(1e+9) + 7; static int[] sieve; static int ans=1; static ArrayList<Integer> primes; public static void main(String[] args) throws java.lang.Exception { fast s = new fast(); PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); StringBuilder fans = new StringBuilder(); HashMap<String,Integer> hm=new HashMap<String,Integer>(); int n=s.nextInt(); for(int i=0;i<n;i++) { String str=s.nextLine(); if(hm.containsKey(str)) hm.put(str,hm.get(str)+1); else hm.put(str,1); } int c=0; for(int i=0;i<n;i++) { String str=s.nextLine(); if(hm.containsKey(str) && hm.get(str)>=1) hm.put(str, hm.get(str)-1); else c++; } System.out.println(c); } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public static boolean next_permutation(int a[]) { int i=0,j=0;int index=-1; int n=a.length; for(i=0;i<n-1;i++) if(a[i]<a[i+1]) index=i; if(index==-1) return false; i=index; for(j=i+1;j<n && a[i]<a[j];j++); int temp=a[i]; a[i]=a[j-1]; a[j-1]=temp; for(int p=i+1,q=n-1;p<q;p++,q--) { temp=a[p]; a[p]=a[q]; a[q]=temp; } return true; } public static void division(char ch[],int divisor) { int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0; StringBuilder quotient=new StringBuilder(""); for(int i=1;i<ch.length;i++) { div=div*mul+Character.getNumericValue(ch[i]); if(div<divisor) {quotient.append("0");continue;} quotient.append(div/divisor); div=div%divisor;mul=10; } remainder=div; while(quotient.charAt(0)=='0')quotient.deleteCharAt(0); System.out.println(quotient+" "+remainder); } public static void sieve(int size) { sieve=new int[size+1]; primes=new ArrayList<Integer>(); sieve[1]=1; for(int i=2;i<=Math.sqrt(size);i++) { if(sieve[i]==0) { for(int j=i*i;j<size;j+=i) sieve[j]=1; } } for(int i=2;i<=size;i++) { if(sieve[i]==0) primes.add(i); } } public static long pow(long n, long b, long MOD) { long x=1;long y=n; while(b > 0) { if(b%2 == 1) { x=x*y; if(x>MOD) x=x%(MOD); } y = y*y; if(y>MOD) y=y%(MOD); b >>= 1; } return x; } public static int upper(Integer[] a,int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]<key) {return -1;} if(start>end) return -1; if(a[mid]>=key && (((mid-1)>=0 && a[mid-1]<key) || (mid-1)==0)) return mid; else if(a[mid]== key && (mid-1)>=0 && a[mid-1]==key) return lower(a,start,mid-1,key); else if(key>a[mid]) return lower(a,mid+1,end,key); else return lower(a,start,mid-1,key); } public static int lower(Integer a[],int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]>key) {return -1;} if(start>end) return -1; if(a[mid]<=key && (((mid+1)<a.length && a[mid+1]>key) || (mid+1)==a.length)) return mid; else if(a[mid]== key && (mid+1)<a.length && a[mid+1]==key) return upper(a,mid+1,end,key); else if(key>=a[mid]) return upper(a,mid+1,end,key); else return upper(a,start,mid-1,key); } public int gcd(int a,int b) { if(a==0) return b; return gcd(b%a,a); } public fast() { this(System.in); } public fast(InputStream is) { i = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = i.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
797e991f4b2a84d04184a4d30b99cf1e
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; public class Main { static long mod=(long)(1e+9) + 7; static int[] sieve; static int ans=1; static ArrayList<Integer> primes; public static void main(String[] args) throws java.lang.Exception { fast s = new fast(); PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); StringBuilder fans = new StringBuilder(); int n=s.nextInt(); String a[]=new String[n]; String b[]=new String[n]; for(int i=0;i<n;i++) a[i]=s.nextLine(); for(int i=0;i<n;i++) b[i]=s.nextLine(); int c=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(a[i].equals(b[j])) { a[i]=b[j]=""; c++; break; } System.out.println(n-c); } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public static boolean next_permutation(int a[]) { int i=0,j=0;int index=-1; int n=a.length; for(i=0;i<n-1;i++) if(a[i]<a[i+1]) index=i; if(index==-1) return false; i=index; for(j=i+1;j<n && a[i]<a[j];j++); int temp=a[i]; a[i]=a[j-1]; a[j-1]=temp; for(int p=i+1,q=n-1;p<q;p++,q--) { temp=a[p]; a[p]=a[q]; a[q]=temp; } return true; } public static void division(char ch[],int divisor) { int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0; StringBuilder quotient=new StringBuilder(""); for(int i=1;i<ch.length;i++) { div=div*mul+Character.getNumericValue(ch[i]); if(div<divisor) {quotient.append("0");continue;} quotient.append(div/divisor); div=div%divisor;mul=10; } remainder=div; while(quotient.charAt(0)=='0')quotient.deleteCharAt(0); System.out.println(quotient+" "+remainder); } public static void sieve(int size) { sieve=new int[size+1]; primes=new ArrayList<Integer>(); sieve[1]=1; for(int i=2;i<=Math.sqrt(size);i++) { if(sieve[i]==0) { for(int j=i*i;j<size;j+=i) sieve[j]=1; } } for(int i=2;i<=size;i++) { if(sieve[i]==0) primes.add(i); } } public static long pow(long n, long b, long MOD) { long x=1;long y=n; while(b > 0) { if(b%2 == 1) { x=x*y; if(x>MOD) x=x%(MOD); } y = y*y; if(y>MOD) y=y%(MOD); b >>= 1; } return x; } public static int upper(Integer[] a,int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]<key) {return -1;} if(start>end) return -1; if(a[mid]>=key && (((mid-1)>=0 && a[mid-1]<key) || (mid-1)==0)) return mid; else if(a[mid]== key && (mid-1)>=0 && a[mid-1]==key) return lower(a,start,mid-1,key); else if(key>a[mid]) return lower(a,mid+1,end,key); else return lower(a,start,mid-1,key); } public static int lower(Integer a[],int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]>key) {return -1;} if(start>end) return -1; if(a[mid]<=key && (((mid+1)<a.length && a[mid+1]>key) || (mid+1)==a.length)) return mid; else if(a[mid]== key && (mid+1)<a.length && a[mid+1]==key) return upper(a,mid+1,end,key); else if(key>=a[mid]) return upper(a,mid+1,end,key); else return upper(a,start,mid-1,key); } public int gcd(int a,int b) { if(a==0) return b; return gcd(b%a,a); } public fast() { this(System.in); } public fast(InputStream is) { i = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = i.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
a68c7f942f5b0418f90b0b1dd4e342e4
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class Solution { //--------------SOLUTION--------------// public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); new Solver().solve(in , out); out.close(); } private static class Solver { private void solve(InputReader in , PrintWriter out) { int n = in.nextInt(); List<String> last = new ArrayList<>(Arrays.asList(in.nextStringArray(n))); List<String> current = new ArrayList<>(Arrays.asList(in.nextStringArray(n))); for(String size : last) { current.remove(size); } out.println(current.size()); } } //--------------SOLUTION--------------// // EeeeEeEyyYYy bOss cAn i haBE anY pUuSSyYy plssSSsSss // //--------------FAST READER--------------// private static class InputReader { private int pos; private String[] tokens; private BufferedReader reader; private InputReader(InputStream in) { pos = 0; tokens = null; reader = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokens == null || pos == tokens.length) { try { String line = reader.readLine(); tokens = line != null ? line.split("\\s") : null; pos = 0; } catch(IOException e) { e.printStackTrace(); } } return tokens[pos++]; } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++) { a[i] = nextInt(); } return a; } public String[] nextStringArray(int n) { String[] a = new String[n]; for(int i = 0;i < n;i++) { a[i] = next(); } return a; } } //--------------FAST READER--------------// }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
d2980fb6ed67a9154529218afa82804b
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; Solver s = new Solver(); for (int i = 1; i <= t; i++) { s.solve(i, in, out); } out.close(); } } class Solver { void solve(int test, InputReader in, PrintWriter out) { int n = in.nextInt(); String[] a = new String[n], b = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } for (int i = 0; i < n; i++) { b[i] = in.next(); } HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(b[i], map.getOrDefault(b[i], 0) + 1); int ans = 0; for (int i = 0; i < n; i++) { if (map.containsKey(a[i])) { if (map.get(a[i]) > 1) { map.put(a[i], map.get(a[i]) - 1); } else map.remove(a[i]); continue; } ans++; } out.println(ans); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { 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
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
dbfbf3de7ae1167c0b7cc31da13525a8
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); sc.nextLine(); List<String> l1 = new ArrayList<>(); List<String> l2 = new ArrayList<>(); for (int i = 0; i < n; i++) { String tshirtSize = sc.nextLine(); l1.add(tshirtSize); } for (int i = 0; i < n; i++) { String newTshirtSize = sc.nextLine(); l2.add(newTshirtSize); } Collections.sort(l1,(s1, s2) -> { if (s1.length() > s2.length()) { return -1; } else if (s1.length() < s2.length()) { return 1; } else { return s1.compareTo(s2); } }); Collections.sort(l2,(s1, s2) -> { if (s1.length() > s2.length()) { return -1; } else if (s1.length() < s2.length()) { return 1; } else { return s1.compareTo(s2); } }); // String s1 = l1.stream().collect(Collectors.joining("")); // String s2 = l2.stream().collect(Collectors.joining("")); for (int i = 0; i < l2.size(); i++) { if (l1.contains(l2.get(i))) { l1.remove(l2.get(i)); } } System.out.println(l1.size()); sc.close(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
05819f35e4ffc04b0ac828d93cf73698
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); sc.nextLine(); Map<String,Integer> mp1 = new TreeMap<>((s1, s2) -> { if (s1.length() > s2.length()) { return -1; } else if (s1.length() < s2.length()) { return 1; } else { return s1.compareTo(s2); } }); Map<String,Integer> mp2 = new TreeMap<>((s1, s2) -> { if (s1.length() > s2.length()) { return -1; } else if (s1.length() < s2.length()) { return 1; } else { return s1.compareTo(s2); } }); for (int i = 0; i < n; i++) { String tshirtSize = sc.nextLine(); if (mp1.containsKey(tshirtSize)) { mp1.put(tshirtSize,mp1.get(tshirtSize)+1); } else { mp1.put(tshirtSize,1); } } for (int i = 0; i < n; i++) { String newTshirtSize = sc.nextLine(); if (mp1.containsKey(newTshirtSize) && mp1.get(newTshirtSize)>0) { mp1.put(newTshirtSize,mp1.get(newTshirtSize)-1); if (mp1.get(newTshirtSize)==0) { mp1.remove(newTshirtSize); } } else { if (mp2.containsKey(newTshirtSize)) { mp2.put(newTshirtSize,mp2.get(newTshirtSize)+1); } else { mp2.put(newTshirtSize,1); } } } int ans = 0; for (Map.Entry<String,Integer> entry:mp2.entrySet()) { String newts = entry.getKey(); int ts = entry.getValue(); while (ts>0) { String oldts = ((TreeMap<String, Integer>) mp1).firstKey(); for (int i = 0; i < oldts.toCharArray().length; i++) { if (newts.charAt(i) != oldts.charAt(i)) { ans++; } } if (mp1.get(oldts) > 1) { mp1.put(oldts, mp1.get(oldts) - 1); } else { mp1.remove(oldts); } ts--; } } System.out.println(ans); sc.close(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
5aef9a9c992777f0b50ccc24af25bd5c
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
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); ACodehorsesTShirts solver = new ACodehorsesTShirts(); solver.solve(1, in, out); out.close(); } static class ACodehorsesTShirts { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int MA = 0; int XSA[] = new int[4]; int XLA[] = new int[4]; String arr[] = new String[n]; for (int i = 0; i < n; i++) { arr[i] = in.scanString(); } for (int i = 0; i < n; i++) { String str = in.scanString(); if (str.equals("M")) MA++; else { if (str.charAt(str.length() - 1) == 'S') { XSA[str.length() - 1]++; } else { XLA[str.length() - 1]++; } } } int ans = 0; int MB = 0; int XSB[] = new int[4]; int XLB[] = new int[4]; for (int i = 0; i < n; i++) { String str = arr[i]; if (str.equals("M")) MB++; else { if (str.charAt(str.length() - 1) == 'S') { XSB[str.length() - 1]++; } else { XLB[str.length() - 1]++; } } } if (MB > MA) ans += MB - MA; for (int i = 0; i < 4; i++) { if (XLB[i] > XLA[i]) ans += XLB[i] - XLA[i]; if (XSB[i] > XSA[i]) ans += XSB[i] - XSA[i]; } 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; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
bdf2452cc50010f9cbf0e562ebb95543
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
//package com.swiggy.dijkstra; import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH; import java.awt.event.TextEvent; import java.io.*; import java.util.*; public class ModifyLongest { InputStream is; PrintWriter out; String INPUT = ""; //boolean codechef=true; boolean codechef=true; void solve() { int n=ni(); String[] a=new String[n]; String[] b=new String[n]; int[][] cnta=new int[4][3]; int[][] cntb=new int[4][3]; for(int i=0;i<n;i++) { a[i]=ns(); int len=a[i].length(); if(a[i].charAt(len-1)=='S') { cnta[len-1][0]++; } else if(a[i].charAt(len-1)=='M') { cnta[len-1][1]++; } else { cnta[len-1][2]++; } } for(int i=0;i<n;i++) { b[i]=ns(); int len=b[i].length(); if(b[i].charAt(len-1)=='S') { cntb[len-1][0]++; } else if(b[i].charAt(len-1)=='M') { cntb[len-1][1]++; } else { cntb[len-1][2]++; } } int ans=0; for(int i=0;i<4;i++) { for(int j=0;j<3;j++) { if(cnta[i][j]>cntb[i][j])ans+=cnta[i][j]-cntb[i][j]; } } System.out.println(ans); } static int ans; static int comp(int u,boolean[] vis,Edge[][] g) { vis[u]=true; int sum=0; for(Edge ed:g[u]) { int end=ed.end; if(!vis[end]) { int val=comp(ed.end,vis,g); if(val%2==0) { ans++; } else sum+=val; } } return sum+1; } static class Edge { int end; int odd; int sum; } static int[][] packD(int[] from,int[] to,int n) { int len=from.length; int[] cnt=new int[n]; for(int i=0;i<len;i++) { cnt[from[i]]++; } int[][] graph=new int[n][]; for(int i=0;i<n;i++) { graph[i]=new int[cnt[i]]; } int[] ind=new int[n]; for(int i=0;i<len;i++) { graph[from[i]][ind[from[i]]++]=to[i]; } return graph; } static class Temp { int ind; int val; public Temp(int ind,int val) { this.ind=ind; this.val=val; } } static HashMap<Integer,Integer> map; static void rev(char[] arr,int st,int end) { int len=(end-st+1); for(int i=st;i<st+len/2;i++) { char tmp=arr[i]; arr[i]=arr[end]; arr[end]=tmp; end--; } } static long fnc(int a,int b) { long val=Math.min(a,b)*1000000007; val+=Math.max(a,b); return val; } static long fnc2(int a,int b) { long val=a*1000000007; val+=b; return val; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; } } static int bit[]; static void add(int x,int d,int n) { for(int i=x;i<=n;i+=i&-i)bit[i]+=d; } static int query(int x) { int ret=0; for(int i=x;i>0;i-=i&-i) ret+=bit[i]; return ret; } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static int gcd(int a,int b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } void run() throws Exception { if(codechef)oj=true; 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 ModifyLongest().run();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
f25b8370a6b8e15084dab07d0476621e
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
//CREATED BY : AMBIKESH JHA //NEPAL //Never Give Up Trying... //Code Begins Here import java.io.*; import java.util.*; import java.lang.*; public class Solution{ static final BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static final BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); static int tc; static String[] s; public static void main(String[] args)throws IOException{ tc=1; //tc=Integer.parseInt(br.readLine()); while(tc-->0){ int N=Integer.parseInt(br.readLine()); ArrayList<String> al=new ArrayList<>(); ArrayList<String> bl=new ArrayList<>(); for(int i=0;i<N;i++){ al.add(br.readLine()); } for(int i=0;i<N;i++){ bl.add(br.readLine()); } for(int i=0;i<al.size();i++){ for(int j=0;j<bl.size();j++){ if(al.get(i).equals(bl.get(j))){ al.set(i,"Z"); bl.set(j,"Z"); break; } } } al.removeIf("Z"::equals); bl.removeIf("Z"::equals); al.sort(Comparator.comparing(String::length)); bl.sort(Comparator.comparing(String::length)); int count=0; out.write(al.size()+"\n"); } out.close(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
cd9183ab4b458e4d3ba161bedfc96f82
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Solution{ static final BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static final BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); static int tc; static String[] s; public static void main(String[] args)throws IOException{ tc=1; //tc=Integer.parseInt(br.readLine()); while(tc-->0){ int N=Integer.parseInt(br.readLine()); ArrayList<String> al=new ArrayList<>(); ArrayList<String> bl=new ArrayList<>(); for(int i=0;i<N;i++){ al.add(br.readLine()); } for(int i=0;i<N;i++){ bl.add(br.readLine()); } for(int i=0;i<al.size();i++){ for(int j=0;j<bl.size();j++){ if(al.get(i).equals(bl.get(j))){ al.set(i,"Z"); bl.set(j,"Z"); break; } } } al.removeIf("Z"::equals); bl.removeIf("Z"::equals); //al.sort(Comparator.comparing(String::length)); //bl.sort(Comparator.comparing(String::length)); //int count=0; out.write(al.size()+"\n"); } out.close(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
5f1f10807725c502c9070aeddea25529
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
//CREATED BY : AMBIKESH JHA //NEPAL //Never Give Up Trying... //Code Begins Here import java.io.*; import java.util.*; import java.lang.*; public class Solution{ static final BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static final BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); static int tc; static String[] s; public static void main(String[] args)throws IOException{ tc=1; //tc=Integer.parseInt(br.readLine()); while(tc-->0){ int N=Integer.parseInt(br.readLine()); ArrayList<String> al=new ArrayList<>(); ArrayList<String> bl=new ArrayList<>(); for(int i=0;i<N;i++){ al.add(br.readLine()); } for(int i=0;i<N;i++){ bl.add(br.readLine()); } for(int i=0;i<al.size();i++){ for(int j=0;j<bl.size();j++){ if(al.get(i).equals(bl.get(j))){ al.set(i,"Z"); bl.set(j,"Z"); break; } } } al.removeIf("Z"::equals); bl.removeIf("Z"::equals); out.write(al.size()+"\n"); } out.close(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
1ad7530817856af2176347f6a8b56d2e
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.beans.Visibility; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class Main implements Runnable{ public static void main(String[] args) throws IOException { new Thread(null , new Main(),"Main", 1<<26).start(); } public void run(){ try { PrintWriter out = new PrintWriter(System.out); MyScanner sc = new MyScanner(); solve(out, sc); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } void solve(PrintWriter out, MyScanner sc) throws IOException{ int n = sc.nextInt(); Map<String, Integer> a = new HashMap(); Map<String, Integer> b = new HashMap(); for(int i = 0 ; i < n ; ++i) { String s = sc.nextLine(); a.put(s, a.getOrDefault(s, 0) + 1); } for(int i = 0 ; i < n ; ++i) { String s = sc.nextLine(); a.put(s, a.getOrDefault(s, 0) - 1); } int c = 0; for(int cc : a.values()) { if(cc > 0) c += cc; } out.print(c); } } 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
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
d3477989027d6394d4d63f205a9b5802
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.beans.Visibility; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class Main implements Runnable{ public static void main(String[] args) throws IOException { new Thread(null , new Main(),"Main", 1<<26).start(); } public void run(){ try { PrintWriter out = new PrintWriter(System.out); MyScanner sc = new MyScanner(); solve(out, sc); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } void solve(PrintWriter out, MyScanner sc) throws IOException{ int n = sc.nextInt(); Map<String, Integer> a = new HashMap(); Map<String, Integer> b = new HashMap(); for(int i = 0 ; i < n ; ++i) { String s = sc.nextLine(); a.put(s, a.getOrDefault(s, 0) + 1); } for(int i = 0 ; i < n ; ++i) { String s = sc.nextLine(); b.put(s, b.getOrDefault(s, 0) + 1); } int c = 0; int d = a.getOrDefault("X", 0) - b.getOrDefault( "X", 0); c += (d > 0)?d:0; // out.print(c); d = a.getOrDefault("S", 0) - b.getOrDefault( "S", 0); c += (d > 0)?d:0; // out.print(c); d = a.getOrDefault("M", 0) - b.getOrDefault( "M", 0); c += (d > 0)?d:0; // out.print(c); d = a.getOrDefault("L", 0) - b.getOrDefault( "L", 0); c += (d > 0)?d:0; c += Math.abs(a.getOrDefault("XL", 0) - b.getOrDefault( "XL", 0)); c += Math.abs(a.getOrDefault("XXL", 0) - b.getOrDefault( "XXL", 0)); c += Math.abs(a.getOrDefault("XXXL", 0) - b.getOrDefault( "XXXL", 0)); out.print(c); } } 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
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
b695572f0d55af3ee75d2cfe918bc4fa
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.beans.Visibility; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class Main implements Runnable{ public static void main(String[] args) throws IOException { new Thread(null , new Main(),"Main", 1<<26).start(); } public void run(){ try { PrintWriter out = new PrintWriter(System.out); MyScanner sc = new MyScanner(); solve(out, sc); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } void solve(PrintWriter out, MyScanner sc) throws IOException{ int n = sc.nextInt(); Map<String, Integer> a = new HashMap(); String s; for(int i = 0 ; i < n ; ++i) { s = sc.nextLine(); a.put(s, a.getOrDefault(s, 0) + 1); } for(int i = 0 ; i < n ; ++i) { s = sc.nextLine(); a.put(s, a.getOrDefault(s, 0) - 1); } int c = 0; for(int cc : a.values()) { if(cc > 0) c += cc; } out.print(c); } } 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
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
4b9b79059515a0a435f0fe4c29f66618
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class tshirts { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); HashMap<Integer, ArrayList<String>> getLastYrShirtsBasedOnSize = new HashMap<>(); HashMap<Integer, ArrayList<String>> ThisyrShirtsBasedOnSize = new HashMap<>(); boolean sameszie = true; int numchanges = 0; int n = sc.nextInt(); sc.nextLine(); //if(n!=100) { for (int i = 0; i < n; i++) { String p = sc.nextLine(); if (getLastYrShirtsBasedOnSize.containsKey(p.length())) { ArrayList<String> item = getLastYrShirtsBasedOnSize.get(p.length()); item.add(p); getLastYrShirtsBasedOnSize.put(p.length(), item); } else { ArrayList<String> item = new ArrayList<>(); item.add(p); getLastYrShirtsBasedOnSize.put(p.length(), item); } } for (int i = 0; i < n; i++) { String p = sc.nextLine(); if (ThisyrShirtsBasedOnSize.containsKey(p.length())) { ArrayList<String> item = ThisyrShirtsBasedOnSize.get(p.length()); item.add(p); ThisyrShirtsBasedOnSize.put(p.length(), item); } else { if (!getLastYrShirtsBasedOnSize.containsKey(p.length())) { sameszie = false; } ArrayList<String> item = new ArrayList<>(); item.add(p); ThisyrShirtsBasedOnSize.put(p.length(), item); } } if (sameszie) { HashSet<Integer> lookTrhought = new HashSet(getLastYrShirtsBasedOnSize.keySet()); for (Integer p : lookTrhought) { ArrayList<String> old = getLastYrShirtsBasedOnSize.get(p); ArrayList<String> newyr = ThisyrShirtsBasedOnSize.get(p); for (int i = 0; i < old.size(); i++) { if (newyr.contains(old.get(i))) { newyr.remove(old.get(i)); old.remove(old.get(i)); i--; } } //if(n==100) //System.out.println(old + "" + newyr); if (p >= 2) { numchanges += old.size(); } else { numchanges += old.size(); } } } System.out.println(numchanges); System.out.println(); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
31399121f5324283e5e9b9a37aecde4d
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.*; public class Shirts{ public static void main(String[]args){ Scanner s=new Scanner(System.in); int n = s.nextInt();//number of winners. String [] x = new String[n]; String [] y = new String[n]; String [] z = {"XXXS","XXS","XS","S","M","L","XL","XXL","XXXL"}; for(int i=0;i<n;++i) x[i] = s.next(); for(int j=0;j<n;++j) y[j] = s.next(); seconds(x,y,z,n); } public static void seconds(String []x,String []y,String [] z,int n){ boolean flagB = true; boolean flagA = false; int s;//counter x int t;//counter y int v=0;//seconds String a =""; for(int i=0;i<n;++i){ s = 1; t = 0; flagB = true; flagA = false; a = x[i]; for(int m=0; m<z.length && flagA==false;++m){ if (a.equals(z[m])){ z[m]="Done"; flagB = true; flagA = true; } else flagB = false; } for(int j=i;j<n && flagB==true;++j){ if(i==j) continue; else if(a.equals(x[j])) ++s; } for(int q=0; q<n && flagB==true;++q){ if(a.equals(y[q])) ++t; } if (s>t && flagB==true) v = v + (s-t); else if (t<s && flagB==true) v = v + (t-s); } System.out.println(v); return; } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
04e75a2da60034dd589707e02db639ae
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.util.*; import java.io.*; public class main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); PrintWriter p=new PrintWriter(System.out); ArrayList<String>arr=new ArrayList<>(); int n=sc.nextInt(); String s; for(int i=0;i<n;i++)arr.add(sc.next()); for(int i=0;i<n;i++) { s=sc.next(); if(arr.contains(s))arr.remove(s); } System.out.println(arr.size()); } }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
562e18e0aa158048b77bed0d3e82e482
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.util.*; public class one { static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 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 char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = new Integer(this.nextInt()); } return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } } public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); String str1[] = new String[N]; String str2[] = new String[N]; HashMap<String, Integer> map = new HashMap<>(); // int k=in.nextInt(); long FinalAns = 0; for (int i = 0; i < N; i++) str1[i] = in.next(); for (int i = 0; i < N; i++) { str2[i] = in.next(); if (map.containsKey(str2[i])) map.put(str2[i], map.get(str2[i]) + 1); else map.put(str2[i], 1); } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < N; i++) { if (map.containsKey(str1[i]) && map.get(str1[i]) >= 1) map.put(str1[i], map.get(str1[i]) - 1); else { arr.add(i); } } for (int i = 0; i < arr.size(); i++) { String Test = str1[arr.get(i)]; String check = ""; for (int j = 0; j < Test.length()-1; j++) check += Test.charAt(j); if (Test.length() == 1) { if (map.containsKey("S") && map.get("S") >= 1 && Test.charAt(0)!='S' ){ map.put("S", map.get("S") - 1); FinalAns++; } else if (map.containsKey("L") && map.get("L") >= 1 && Test.charAt(0)!='L' ) { map.put("L", map.get("L") - 1); FinalAns++; } else if (map.containsKey("M") && map.get("M") >= 1 && Test.charAt(0)!='M' ) { map.put("M", map.get("M") - 1); FinalAns++; } } else { if (Test.charAt(Test.length() - 1) == 'S') check += 'L'; else check += 'S'; if (map.containsKey(check)) { map.put(check, map.get(check) - 1); FinalAns++; } } } System.out.println(FinalAns); } //System.out.println(FinalAns); }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
f4ebb38fb602ef8d597ad30f57b1ec6a
train_002.jsonl
1530110100
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
256 megabytes
import java.io.*; import java.util.*; public class one { static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 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 char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = new Integer(this.nextInt()); } return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } } public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); String str1[] = new String[N]; String str2[] = new String[N]; HashMap<String, Integer> map = new HashMap<>(); // int k=in.nextInt(); long FinalAns = 0; for (int i = 0; i < N; i++) str1[i] = in.next(); for (int i = 0; i < N; i++) { str2[i] = in.next(); if (map.containsKey(str2[i])) map.put(str2[i], map.get(str2[i]) + 1); else map.put(str2[i], 1); } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < N; i++) { if (map.containsKey(str1[i]) && map.get(str1[i]) >= 1) map.put(str1[i], map.get(str1[i]) - 1); else { arr.add(i); } } for (int i = 0; i < arr.size(); i++) { String Test = str1[arr.get(i)]; String check = ""; for (int j = 0; j < Test.length()-1; j++) check += Test.charAt(j); if (Test.length() == 1) { if (map.containsKey("S") && map.get("S") >= 1 && Test.charAt(0)!='S' ){ map.put("S", map.get("S") - 1); FinalAns++; } else if (map.containsKey("L") && map.get("L") >= 1 && Test.charAt(0)!='L' ) { map.put("L", map.get("L") - 1); FinalAns++; } else if (map.containsKey("M") && map.get("M") >= 1 && Test.charAt(0)!='M' ) { map.put("M", map.get("M") - 1); FinalAns++; } } else { if (Test.charAt(Test.length() - 1) == 'S') check += 'L'; else check += 'S'; if (map.containsKey(check)) { map.put(str1[i], map.get(check) - 1); FinalAns++; } } } System.out.println(arr.size()); } //System.out.println(FinalAns); }
Java
["3\nXS\nXS\nM\nXL\nS\nXS", "2\nXXXL\nXXL\nXXL\nXXXS", "2\nM\nXS\nXS\nM"]
2 seconds
["2", "1", "0"]
NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.
Java 8
standard input
[ "implementation", "greedy" ]
c8321b60a6ad04093dee3eeb9ee27b6f
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.
1,200
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
standard output
PASSED
779250a3d807b1547803bd9946b2e30c
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
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.ArrayDeque; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class e { static long MOD = 1_000_000_007; public static void main(String[] args) { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); long S = in.nextLong(); VecL[] vecs = new VecL[n]; for(int i = 0; i < n; i++) vecs[i] = new VecL(in.nextLong(), in.nextLong()); VecL[] conv = ConvexHull.getHull(vecs); int[] points = new int[3]; points[0] = 0; points[1] = 1; points[2] = 2; n = conv.length; int ind = 2; int num = 0; while(true) { int dist = 0; while(true) { long curr = area(conv[points[0]], conv[points[1]], conv[points[2]]); points[ind] = (points[ind]+1)%n; if(area(conv[points[0]], conv[points[1]], conv[points[2]]) <= curr) break; dist++; } points[ind] = (points[ind]+n-1)%n; while(true) { long curr = area(conv[points[0]], conv[points[1]], conv[points[2]]); points[ind] = (points[ind]+n-1)%n; if(area(conv[points[0]], conv[points[1]], conv[points[2]]) <= curr) break; dist++; } points[ind] = (points[ind]+1)%n; ind = (ind+1)%3; if(dist == 0) { num++; if(num == 4) break; } else { num = 0; } } out.println(conv[points[0]].x+conv[points[2]].x-conv[points[1]].x+" "+(conv[points[0]].y+conv[points[2]].y-conv[points[1]].y)); out.println(conv[points[1]].x+conv[points[0]].x-conv[points[2]].x+" "+(conv[points[1]].y+conv[points[0]].y-conv[points[2]].y)); out.println(conv[points[1]].x+conv[points[2]].x-conv[points[0]].x+" "+(conv[points[1]].y+conv[points[2]].y-conv[points[0]].y)); out.close(); } static long area(VecL a, VecL b, VecL c) { return Math.abs(a.cross(b)+b.cross(c)+c.cross(a)); } static class ConvexHull { static VecL[] upperHull, lowerHull; public static VecL[] removeDupes(VecL[] points) { HashSet<VecL> set = new HashSet<>(); for (VecL v : points) { set.add(v); } int counter = 0; points = new VecL[set.size()]; for (VecL v : set) { points[counter++] = v; } return points; } // returns the hull in CCW order public static VecL[] getHull(VecL[] points) { points = points.clone(); Arrays.sort(points); if (points.length < 3) { return upperHull = lowerHull = points; } int n = points.length, j = 2, k = 2; VecL[] lo = new VecL[n], up = new VecL[n]; lo[0] = points[0]; lo[1] = points[1]; for (int i = 2; i < n; i++) { VecL p = points[i]; while (j > 1 && !right(lo[j - 2], lo[j - 1], p)) { j--; } lo[j++] = p; } up[0] = points[n - 1]; up[1] = points[n - 2]; for (int i = n - 3; i >= 0; i--) { VecL p = points[i]; while (k > 1 && !right(up[k - 2], up[k - 1], p)) { k--; } up[k++] = p; } VecL[] res = new VecL[j + k - 2]; for (int i = 0; i < k; i++) { res[i] = up[i]; } for (int i = 1; i < j - 1; i++) { res[k + i - 1] = lo[i]; } // if you need upper and lower hulls upperHull = new VecL[k]; for (int i = 0; i < k; i++) { upperHull[i] = up[k - i - 1]; } lowerHull = new VecL[j]; for (int i = 0; i < j; i++) { lowerHull[i] = lo[i]; } return res; } // check if a->b->c are in the right order static boolean right(VecL a, VecL b, VecL c) { return b.sub(a).cross(c.sub(a)) > 0; } } static class VecL implements Comparable<VecL> { long x, y; public VecL(long x, long y) { this.x = x; this.y = y; } public VecL add(VecL o) { return new VecL(x + o.x, y + o.y); } public VecL sub(VecL o) { return new VecL(x - o.x, y - o.y); } public VecL scale(long s) { return new VecL(x * s, y * s); } public long dot(VecL o) { return x * o.x + y * o.y; } public long cross(VecL o) { return x * o.y - y * o.x; } public long mag2() { return dot(this); } public VecL rot90() { return new VecL(-y, x); } public VecL rot270() { return new VecL(y, -x); } public String toString() { return "(" + x + ", " + y + ")"; } public int hashCode() { return Long.hashCode(x << 13 ^ (y * 57)); } public boolean equals(Object oo) { VecL o = (VecL) oo; return x == o.x && y == o.y; } public int compareTo(VecL o) { if (x != o.x) { return Long.compare(x, o.x); } return Long.compare(y, o.y); } //origin->q1, axes-> quadrant in ccw direction public int quadrant() { if (x == 0 || y == 0) { if (y == 0) { if (x >= 0) { return 1; } else { return 3; } } else if (y >= 0) { return 2; } else { return 4; } } if (x > 0) { if (y > 0) { return 1; } else { return 4; } } else if (y > 0) { return 2; } else { return 3; } } public int radialCompare(VecL o) { if (quadrant() == o.quadrant()) { return -Long.signum(cross(o)); } return Integer.compare(quadrant(), o.quadrant()); } } static class FS { BufferedReader in; StringTokenizer token; public FS(InputStream str) { in = new BufferedReader(new InputStreamReader(str)); } public String next() { if (token == null || !token.hasMoreElements()) { try { token = new StringTokenizer(in.readLine()); } catch (IOException ex) { } return next(); } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
af21eb9a0d094ea6c3a1451bc02d2a04
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); int numOfPoints = r.nextInt(); r.nextLong(); Point[] yarra = new Point[numOfPoints]; for(int i = 0; i < numOfPoints; i++) { yarra[i] = new Point(r.nextLong(), r.nextLong()); } yarra = convexHull(yarra); long best = -1; int[] BEST = new int[3]; for(int i = 0; i < yarra.length; i++) { int k = i+2; for(int j = i+1; j < yarra.length; j++) { while(k + 1 < yarra.length && cross(yarra[i], yarra[j], yarra[k]) < cross(yarra[i], yarra[j], yarra[k+1])) k++; if(k >= yarra.length) break; long bestNow = cross(yarra[i], yarra[j], yarra[k]); if(bestNow > best) { best = bestNow; BEST = new int[]{i, j, k}; } } } Point[] woo = convexHull(new Point[]{yarra[BEST[0]], yarra[BEST[1]], yarra[BEST[2]]}); System.out.println((woo[0].x + woo[1].x - woo[2].x) + " " + (woo[0].y + woo[1].y - woo[2].y)); System.out.println((-woo[0].x + woo[1].x + woo[2].x) + " " + (-woo[0].y + woo[1].y + woo[2].y)); System.out.println((woo[0].x - woo[1].x + woo[2].x) + " " + (woo[0].y - woo[1].y + woo[2].y)); } public static Point[] convexHull(Point p[]) { int n = p.length, k = 0; if(n <= 1) return p; Arrays.sort(p); // sort by x then y Point h[] = new Point[2* n]; // use (> -EPS) forclockwise, (< EPS)for CCW // to include collinear points, flip sign of EPS for(int i = 0; i < n; h[k++] = p[i++]) while(k >= 2 && cross(h[k-2], h[k-1], p[i]) <= 0) --k; for(int i = n-2, t = k; i >= 0; h[k++] = p[i--]) while(k>t && cross(h[k-2], h[k-1], p[i]) <= 0) --k; k -= 1 +(h[0] == h[1]? 1: 0); // no need for EPS return Arrays.copyOf(h, k); } static class Point implements Comparable<Point> { long x, y; public Point(long x, long y) { this.x = x; this.y = y; } public int compareTo(Point p) { if(x == p.x) return Long.compare(y, p.y); return Long.compare(x, p.x); } } public static long cross(Point a, Point b, Point c) { return cross(a, b) + cross(b, c) + cross(c, a); } public static long cross(Point a, Point b) { return a.x * b.y -a.y * b.x; } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
19e67c22f6ebba0f3940c1365fbf7117
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class E { FastScanner scanner; PrintWriter writer; static class Point implements Comparable<Point> { long x, y; public Point(long x, long y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { if (x < o.x || x == o.x && y < o.y) return -1; else if (x == o.x && y == o.y) return 0; else return 1; } } enum Or { L, R, C } long sq(Point p1, Point p2, Point p3) { return (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x); } Or or(Point p1, Point p2, Point p3) { long s = sq(p1, p2, p3); if (s < 0) return Or.R; else if (s == 0) return Or.C; else return Or.L; } <T> void shuffle(List<T> l) { Random random = new Random(System.currentTimeMillis()); for (int i = 1; i < l.size(); i++) { int j = random.nextInt(i + 1); T tmp = l.get(i); l.set(i, l.get(j)); l.set(j, tmp); } } Point[] findTri(List<Point> pts) { Point[] tri = new Point[] {pts.get(0), pts.get(1), pts.get(2)}; boolean change = true; long curS = Math.abs(sq(tri[0], tri[1], tri[2])); while (change) { change = false; for (Point p : pts) { for (int i = 0; i < 3; i++) { Point a = tri[(i + 1) % 3]; Point b = tri[(i + 2) % 3]; long newS = Math.abs(sq(a, b, p)); if (newS > curS) { tri[i] = p; curS = newS; change = true; break; } } } } if (or(tri[0], tri[1], tri[2]) == Or.R) { Point tmp = tri[1]; tri[1] = tri[2]; tri[2] = tmp; } return tri; } Point add(Point p, Point vb, Point ve) { long x = p.x + ve.x - vb.x; long y = p.y + ve.y - vb.y; return new Point(x, y); } void solve() throws IOException { scanner = new FastScanner(System.in); writer = new PrintWriter(System.out); int n = scanner.nextInt(); long s = scanner.nextLong(); List<Point> pts = new ArrayList<>(); for (int i = 0; i < n; i++) { long x = scanner.nextLong(); long y = scanner.nextLong(); Point p = new Point(x, y); pts.add(p); } Point[] tri = findTri(pts); Point a = add(tri[0], tri[1], tri[2]); Point b = add(tri[0], tri[2], tri[1]); Point c = add(tri[1], tri[0], tri[2]); writer.println(a.x + " " + a.y); writer.println(b.x + " " + b.y); writer.println(c.x + " " + c.y); writer.close(); } public static void main(String... args) throws IOException { new E().solve(); } static class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(String fileName) throws FileNotFoundException { this(new FileInputStream(new File(fileName))); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
88857a204b470ebf7a678381751c403b
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.util.*; import java.io.*; import java.awt.*; public class AlyonaTr { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int m = Integer.parseInt(st.nextToken()); st.nextToken(); // char[][] map = new char[200][200]; for(int i = 0; i < 200; i++) Arrays.fill(map[i], '.'); Point[] psp = new Point[m]; for(int i = 0; i < m; i++){ st = new StringTokenizer(br.readLine()); psp[i] = new Point(); psp[i].x = Integer.parseInt(st.nextToken()); psp[i].y = Integer.parseInt(st.nextToken()); // map[psp[i].x+100][psp[i].y+100] = 'º'; } Point[] ps = ConvexHull.ch(psp); int n = ps.length; // for(Point p: ps) map[p.x+100][p.y+100] = 'H'; int a = 0; int b = 1; int c = 2; long maxarea = area(ps,a,b,c); for(int i = 0; i < n-2; i++){ int j = i+1; int k = i+2; while(j < n-1){ while(k < n-1 && area(ps,i,j,k) < area(ps,i,j,k+1)) k++; if(area(ps,i,j,k) > maxarea){ a = i; b = j; c = k; maxarea = area(ps,i,j,k); } j++; } } Point pA = ps[a]; Point pB = ps[b]; Point pC = ps[c]; //pA + pC - pB long ax = (pA.x + pB.x - pC.x); long ay = (pA.y + pB.y - pC.y); System.out.println(ax+" "+ay); //pB + pA - pC System.out.println((pB.x + pC.x - pA.x)+" "+(pB.y + pC.y - pA.y)); //pC + pB - pA System.out.println((pC.x + pA.x - pB.x)+" "+(pC.y + pA.y - pB.y)); Point p1 = new Point((pA.x + pB.x - pC.x),(pA.y + pB.y - pC.y)); Point p2 = new Point((pB.x + pC.x - pA.x),(pB.y + pC.y - pA.y)); Point p3 = new Point((pC.x + pA.x - pB.x),(pC.y + pA.y - pB.y)); // if(m <= 5000){ // System.out.println(""); // StringBuilder sb = new StringBuilder(); // for(int i = 0; i < m; i++){ // if(!inside(p1, p2, p3, psp[i])) sb.append(psp[i]+"\n"); // } // System.out.println(sb.toString().trim()); // } // // // for(int i = 0; i < 200; i++) System.out.println(new String(map[i])); } public static boolean inside(Point A, Point B, Point C, Point O){ if(cross(O,A,B)>=0 && cross(O,B,C)>=0 && cross(O,C,A)>=0) return true; else return false; } public static long area(Point[] ps, int i, int j, int k){ return area(ps[i],ps[j],ps[k]); } public static long area(Point O, Point A, Point B){ return Math.abs(cross(O,A,B)); } public static long cross(Point O, Point A, Point B){ return (long)((long)A.x-(long)O.x)*((long)B.y-(long)O.y) - (long)((long)A.y-(long)O.y)*((long)B.x-(long)O.x); } static class ConvexHull{ public static Point[] ch(Point[] P){ if(P.length <= 1) return P; int n = P.length, k = 0; Point[] H = new Point[2*n]; Arrays.sort(P); for(int i = 0; i < n; i++){ while(k >= 2 && cross(H[k-2],H[k-1],P[i])<=0) k--; H[k++] = P[i]; } for(int i = n-2, t = k+1; i>=0; i--){ while(k >= t && cross(H[k-2],H[k-1],P[i])<=0) k--; H[k++] = P[i]; } if(k > 1){ H = Arrays.copyOfRange(H, 0, k-1); } return H; } } static class Point implements Comparable<Point>{ int x, y; public Point(){}; public Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o){ if(x == o.x) return y - o.y; else return x - o.x; } public String toString(){ return x+" "+y; } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
81952bdfad259553c9417fb298fb6b4a
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
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 static java.lang.Math.abs; import static java.lang.Math.sqrt; import java.util.Scanner; /** * * @author ANDRES */ public class AAAA { //Convex husk->Suplementary triangle static int cont; Scanner sc; int n; long s; long px[]; long py[]; int bax,bay,bbx,bby,bcx,bcy; double maxArea; int a,b,c; AAAA(){ sc = new Scanner(System.in); n = sc.nextInt(); s = sc.nextLong(); px = new long[n]; py = new long[n]; cont = 1; for(int i =0;i<n;i++){ px[i] = sc.nextInt(); py[i] = sc.nextInt(); } a = 0; b = 1; c = 2; int flag = 0; while(true){ flag = 0; for(int i = 0;i<n;i++){ if(Area(px[i],py[i],px[b],py[b],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ a = i; flag =1; } if(Area(px[a],py[a],px[i],py[i],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ b = i; flag = 1; } if(Area(px[a],py[a],px[b],py[b],px[i],py[i])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ c = i; flag =1; } } if(flag == 0){ break; } } System.out.println(((px[c]-px[a])+px[b])+" "+((py[b]-py[a])+py[c])); System.out.println(((px[a]-px[c])+px[b])+" "+((py[b]-py[c])+py[a])); System.out.println(((px[c]-px[b])+px[a])+" "+((py[c]-py[b])+py[a])); } double Area(long ax,long ay,long bx,long by, long cx,long cy){ //100%funcional long A; long B; double lad1,lad2,lad3,semp,area; A = abs(ax - bx); B = abs(ay - by); lad1 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(ax - cx); B = abs(ay - cy); lad2 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(bx - cx); B = abs(by - cy); lad3 = (sqrt((double)(A*A)+(double)(B*B))); semp = (lad1+lad2+lad3)/2; area = sqrt(semp*(semp-lad1)*(semp-lad2)*(semp-lad3)); return area; } public static void main(String args[]){ AAAA a = new AAAA(); } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
07ab0f3e0698ca808a9e66eb4ae1ce01
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
//package round358; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class E2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); long S = nl(); long[][] co = new long[n][]; for(int i = 0;i < n;i++){ co[i] = new long[]{ni(), ni()}; } co = convexHull(co); long maxs = -1L; int bi = -1, bj = -1, bk = -1; int m = co.length; for(int i = 0;i < m;i++){ int k = i; for(int j = i;j < m;j++){ if(k < j)k = j; long curs = S(co[i], co[j], co[k]); while(k+1 < m){ long nexs = S(co[i], co[j], co[k+1]); if(nexs > curs){ curs = nexs; k++; }else{ break; } } // tr(i, j, k, curs); if(curs > maxs){ maxs = curs; bi = i; bj = j; bk = k; } } } long ax = co[bi][0] + (co[bj][0]-co[bi][0]) + (co[bk][0]-co[bi][0]); long ay = co[bi][1] + (co[bj][1]-co[bi][1]) + (co[bk][1]-co[bi][1]); long bx = co[bi][0] + (co[bj][0]-co[bi][0]) - (co[bk][0]-co[bi][0]); long by = co[bi][1] + (co[bj][1]-co[bi][1]) - (co[bk][1]-co[bi][1]); long cx = co[bi][0] - (co[bj][0]-co[bi][0]) + (co[bk][0]-co[bi][0]); long cy = co[bi][1] - (co[bj][1]-co[bi][1]) + (co[bk][1]-co[bi][1]); out.println(ax + " " + ay); out.println(bx + " " + by); out.println(cx + " " + cy); // check(ax, ay, bx, by, cx, cy, co, maxs); } void check(long ax, long ay, long bx, long by, long cx, long cy, long[][] co, long maxs) { int n = co.length; for(int i = 0;i < n;i++){ int ccws = 0; { int cw = ccw(co[i][0], co[i][1], ax, ay, bx, by); if(cw == 0)continue; ccws += cw; } { int cw = ccw(co[i][0], co[i][1], bx, by, cx, cy); if(cw == 0)continue; ccws += cw; } { int cw = ccw(co[i][0], co[i][1], cx, cy, ax, ay); if(cw == 0)continue; ccws += cw; } if(ccws == 3 || ccws == -3){ }else{ tr(ax, ay, bx, by, cx, cy, co[i]); throw new RuntimeException(); } } long us = S(new long[]{ax, ay}, new long[]{bx, by}, new long[]{cx, cy}); if(us > 4*maxs){ tr(us, maxs); throw new RuntimeException(); } } long S(long[] a, long[] b, long[] c) { long ax = b[0]-a[0]; long ay = b[1]-a[1]; long bx = c[0]-a[0]; long by = c[1]-a[1]; return Math.abs(ax*by-bx*ay); } public static int ccw(long ax, long ay, long bx, long by, long tx, long ty) { return Long.signum((tx - ax) * (by - ay) - (bx - ax) * (ty - ay)); } public static Comparator<long[]> compArgi = new Comparator<long[]>(){ public int compare(long[] a, long[] b) { long ax = a[0], ay = a[1]; long bx = b[0], by = b[1]; int za = ay > 0 || (ay == 0 && ax > 0) ? 0 : 1; int zb = by > 0 || (by == 0 && bx > 0) ? 0 : 1; if(za != zb)return za - zb; return Long.signum(ay*bx-ax*by); } }; public static long[][] convexHull(long[][] co) { int n = co.length; if(n <= 1)return co; Arrays.sort(co, new Comparator<long[]>(){ public int compare(long[] a, long[] b){ if(a[0] != b[0])return Long.compare(a[0], b[0]); return Long.compare(a[1], b[1]); } }); int[] inds = new int[n + 1]; int p = 0; for(int i = 0;i < n;i++){ if(p >= 1 && co[inds[p-1]][0] == co[i][0] && co[inds[p-1]][1] == co[i][1])continue; while(p >= 2 && ccw(co[inds[p-2]], co[inds[p-1]], co[i]) >= 0)p--; // if you need point on line inds[p++] = i; } int inf = p + 1; for(int i = n - 2;i >= 0;i--){ if(co[inds[p-1]][0] == co[i][0] && co[inds[p-1]][1] == co[i][1])continue; while(p >= inf && ccw(co[inds[p-2]], co[inds[p-1]], co[i]) >= 0)p--; // if you need point on line inds[p++] = i; } long[][] ret = new long[p-1][]; for(int i = 0;i < p-1;i++)ret[i] = co[inds[i]]; return ret; } public static int ccw(long[] a, long[] b, long[] t) { return Long.signum((t[0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (t[1] - a[1])); } 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 E2().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))){ // 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
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
b483d51d02d586a5fddee0ea481236d1
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class E { private static class Task { void solve(FastScanner in, PrintWriter out) { int N = in.nextInt(); long S = in.nextLong(); Long[][] xy = new Long[N][]; for (int i = 0; i < N; i++) xy[i] = new Long[]{in.nextLong(), in.nextLong()}; ArrayList<Long[]> convexHull = ConvexHull.run(xy); long max = -1L; int ti = -1, tj = -1, tk = -1; int m = convexHull.size(); for (int i = 0; i < m; i++) { int k = i; for (int j = i; j < m; j++) { if (k < j) k = j; long curs = S(convexHull.get(i), convexHull.get(j), convexHull.get(k)); while (k + 1 < m) { long next = S(convexHull.get(i), convexHull.get(j), convexHull.get(k + 1)); if (next > curs) { curs = next; k++; } else { break; } } if (curs > max) { max = curs; ti = i; tj = j; tk = k; } } } Long[] ci = convexHull.get(ti), cj = convexHull.get(tj), ck = convexHull.get(tk); long ax = ci[0] + (cj[0] - ci[0]) + (ck[0] - ci[0]); long ay = ci[1] + (cj[1] - ci[1]) + (ck[1] - ci[1]); long bx = ci[0] + (cj[0] - ci[0]) - (ck[0] - ci[0]); long by = ci[1] + (cj[1] - ci[1]) - (ck[1] - ci[1]); long cx = ci[0] - (cj[0] - ci[0]) + (ck[0] - ci[0]); long cy = ci[1] - (cj[1] - ci[1]) + (ck[1] - ci[1]); out.println(ax + " " + ay); out.println(bx + " " + by); out.println(cx + " " + cy); } //abcを結んでできる三角形の面積の2倍を返す long S(Long[] a, Long[] b, Long[] c) { long vx = b[0] - a[0]; long vy = b[1] - a[1]; long wx = c[0] - a[0]; long wy = c[1] - a[1]; return Math.abs(vx * wy - vy * wx); } } static class ConvexHull { public static <T extends Number> ArrayList<T[]> run(T[][] xy) { int N = xy.length; if (N <= 1) { ArrayList<T[]> list = new ArrayList<>(); Collections.addAll(list, xy); return list; } Arrays.sort(xy, new Comparator<T[]>() { @Override public int compare(T[] a, T[] b) { if (!a[0].equals(b[0])) return Double.compare(a[0].doubleValue(), b[0].doubleValue()); return Double.compare(a[1].doubleValue(), b[1].doubleValue()); } }); int[] qs = new int[N * 2];//構築中の凸包 int k = 0;//凸包の頂点数 for (int i = 0; i < N; i++) { if (k >= 1 && xy[qs[k - 1]][0].equals(xy[i][0]) && xy[qs[k - 1]][1].equals(xy[i][1])) continue; while (k > 1 && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } int inf = k + 1; for (int i = N - 2; i >= 0; i--) { if (xy[qs[k - 1]][0] == xy[i][0] && xy[qs[k - 1]][1] == xy[i][1]) continue; while (k >= inf && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } ArrayList<T[]> ret = new ArrayList<>(k - 1); for (int i = 0; i < k - 1; i++) ret.add(xy[qs[i]]); return ret; } private static <T extends Number> double ccw(T[] a, T[] b, T[] t) { return (t[0].doubleValue() - a[0].doubleValue()) * (b[1].doubleValue() - a[1].doubleValue()) - (b[0].doubleValue() - a[0].doubleValue()) * (t[1].doubleValue() - a[1].doubleValue()); } } // Template public static void main(String[] args) { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
f0161183c732d0ee301741c36c2457a8
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class E { private static class Task { void solve(FastScanner in, PrintWriter out) { int N = in.nextInt(); long S = in.nextLong(); Long[][] xy = new Long[N][]; for (int i = 0; i < N; i++) xy[i] = new Long[]{in.nextLong(), in.nextLong()}; ArrayList<Long[]> co = ConvexHull.run(xy); long max = -1L; int bi = -1, bj = -1, bk = -1; int m = co.size(); for (int i = 0; i < m; i++) { int k = i; for (int j = i; j < m; j++) { if (k < j) k = j; long curs = S(co.get(i), co.get(j), co.get(k)); while (k + 1 < m) { long nexs = S(co.get(i), co.get(j), co.get(k + 1)); if (nexs > curs) { curs = nexs; k++; } else { break; } } if (curs > max) { max = curs; bi = i; bj = j; bk = k; } } } long ax = co.get(bi)[0] + (co.get(bj)[0] - co.get(bi)[0]) + (co.get(bk)[0] - co.get(bi)[0]); long ay = co.get(bi)[1] + (co.get(bj)[1] - co.get(bi)[1]) + (co.get(bk)[1] - co.get(bi)[1]); long bx = co.get(bi)[0] + (co.get(bj)[0] - co.get(bi)[0]) - (co.get(bk)[0] - co.get(bi)[0]); long by = co.get(bi)[1] + (co.get(bj)[1] - co.get(bi)[1]) - (co.get(bk)[1] - co.get(bi)[1]); long cx = co.get(bi)[0] - (co.get(bj)[0] - co.get(bi)[0]) + (co.get(bk)[0] - co.get(bi)[0]); long cy = co.get(bi)[1] - (co.get(bj)[1] - co.get(bi)[1]) + (co.get(bk)[1] - co.get(bi)[1]); out.println(ax + " " + ay); out.println(bx + " " + by); out.println(cx + " " + cy); } long S(Long[] a, Long[] b, Long[] c) { long vx = b[0] - a[0]; long vy = b[1] - a[1]; long wx = c[0] - a[0]; long wy = c[1] - a[1]; return Math.abs(vx * wy - vy * wx); } } static class ConvexHull { public static <T extends Number> ArrayList<T[]> run(T[][] xy) { int N = xy.length; if (N <= 1) { ArrayList<T[]> list = new ArrayList<>(); Collections.addAll(list, xy); return list; } Arrays.sort(xy, new Comparator<T[]>() { @Override public int compare(T[] a, T[] b) { if (!a[0].equals(b[0])) return Double.compare(a[0].doubleValue(), b[0].doubleValue()); return Double.compare(a[1].doubleValue(), b[1].doubleValue()); } }); int[] qs = new int[N * 2];//構築中の凸包 int k = 0;//凸包の頂点数 for (int i = 0; i < N; i++) { if (k >= 1 && xy[qs[k - 1]][0].equals(xy[i][0]) && xy[qs[k - 1]][1].equals(xy[i][1])) continue; while (k > 1 && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } int inf = k + 1; for (int i = N - 2; i >= 0; i--) { if (xy[qs[k - 1]][0] == xy[i][0] && xy[qs[k - 1]][1] == xy[i][1]) continue; while (k >= inf && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } ArrayList<T[]> ret = new ArrayList<>(k - 1); for (int i = 0; i < k - 1; i++) ret.add(xy[qs[i]]); return ret; } private static <T extends Number> double ccw(T[] a, T[] b, T[] t) { return (t[0].doubleValue() - a[0].doubleValue()) * (b[1].doubleValue() - a[1].doubleValue()) - (b[0].doubleValue() - a[0].doubleValue()) * (t[1].doubleValue() - a[1].doubleValue()); } } // Template public static void main(String[] args) { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
adcd67637fdbe724c71863ea6d96b127
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class E { private static class Task { void solve(FastScanner in, PrintWriter out) { int N = in.nextInt(); long S = in.nextLong(); Long[][] xy = new Long[N][]; for (int i = 0; i < N; i++) xy[i] = new Long[]{in.nextLong(), in.nextLong()}; ArrayList<Point2D.Double> co = new ArrayList<>(); { ArrayList<Long[]> hull = ConvexHull.run(xy); for (Long[] l : hull) { Point2D.Double p = new Point2D.Double(); p.setLocation(l[0], l[1]); co.add(p); } } double max = -1.0; int bi = -1, bj = -1, bk = -1; int m = co.size(); for (int i = 0; i < m; i++) { int k = i; for (int j = i; j < m; j++) { if (k < j) k = j; double curs = S(co.get(i), co.get(j), co.get(k)); while (k + 1 < m) { double nexs = S(co.get(i), co.get(j), co.get(k + 1)); if (nexs > curs) { curs = nexs; k++; } else { break; } } if (curs > max) { max = curs; bi = i; bj = j; bk = k; } } } Point2D pi = co.get(bi), pj = co.get(bj), pk = co.get(bk); double ax = pi.getX() + (pj.getX() - pi.getX()) + (pk.getX() - pi.getX()); double ay = pi.getY() + (pj.getY() - pi.getY()) + (pk.getY() - pi.getY()); double bx = pi.getX() + (pj.getX() - pi.getX()) - (pk.getX() - pi.getX()); double by = pi.getY() + (pj.getY() - pi.getY()) - (pk.getY() - pi.getY()); double cx = pi.getX() - (pj.getX() - pi.getX()) + (pk.getX() - pi.getX()); double cy = pi.getY() - (pj.getY() - pi.getY()) + (pk.getY() - pi.getY()); out.println((long) ax + " " + (long) ay); out.println((long) bx + " " + (long) by); out.println((long) cx + " " + (long) cy); } double S(Point2D a, Point2D b, Point2D c) { double vx = b.getX() - a.getX(); double vy = b.getY() - a.getY(); double wx = c.getX() - a.getX(); double wy = c.getY() - a.getY(); return Math.abs(vx * wy - vy * wx); } } static class ConvexHull { public static <T extends Number> ArrayList<T[]> run(T[][] xy) { int N = xy.length; if (N <= 1) { ArrayList<T[]> list = new ArrayList<>(); Collections.addAll(list, xy); return list; } Arrays.sort(xy, new Comparator<T[]>() { @Override public int compare(T[] a, T[] b) { if (!a[0].equals(b[0])) return Double.compare(a[0].doubleValue(), b[0].doubleValue()); return Double.compare(a[1].doubleValue(), b[1].doubleValue()); } }); int[] qs = new int[N * 2];//構築中の凸包 int k = 0;//凸包の頂点数 for (int i = 0; i < N; i++) { if (k >= 1 && xy[qs[k - 1]][0].equals(xy[i][0]) && xy[qs[k - 1]][1].equals(xy[i][1])) continue; while (k > 1 && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } int inf = k + 1; for (int i = N - 2; i >= 0; i--) { if (xy[qs[k - 1]][0] == xy[i][0] && xy[qs[k - 1]][1] == xy[i][1]) continue; while (k >= inf && ccw(xy[qs[k - 2]], xy[qs[k - 1]], xy[i]) > 0) k--; qs[k++] = i; } ArrayList<T[]> ret = new ArrayList<>(k - 1); for (int i = 0; i < k - 1; i++) ret.add(xy[qs[i]]); return ret; } private static <T extends Number> double ccw(T[] a, T[] b, T[] t) { return (t[0].doubleValue() - a[0].doubleValue()) * (b[1].doubleValue() - a[1].doubleValue()) - (b[0].doubleValue() - a[0].doubleValue()) * (t[1].doubleValue() - a[1].doubleValue()); } } // Template public static void main(String[] args) { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
c90b0853b132b8e52a1c0e4fc141e662
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class AlyonaTriangles { void solve() { int n = in.nextInt(); long s = in.nextLong(); long[][] p = new long[n][2]; for (int i = 0; i < n; i++) { p[i][0] = in.nextInt(); p[i][1] = in.nextInt(); } // find the convex hull for the points long[][] h = convex_hull(p); int m = h.length; // find the max_area triangle from points lie on the convex hull long max = 0; int a = -1, b = -1, c = -1; int i = 0, j = 1, k = 2; while (true) { if (i == m) break; long cur = area(h[i], h[j], h[k]); while (true) { while (true) { int nk = (k + 1) % m; long nxt = area(h[i], h[j], h[nk]); if (nxt >= cur) { k = nk; cur = nxt; } else { break; } } int nj = (j + 1) % m; long nxt = area(h[i], h[nj], h[k]); if (nxt >= cur) { j = nj; cur = nxt; } else { break; } } if (cur > max) { max = cur; a = i; b = j; c = k; } i++; if (j == i) j = (j + 1) % m; if (k == j) k = (k + 1) % m; } // get the anticomplementary triangle from the max_area triangle long[][] res = new long[3][2]; res[0][0] = -h[a][0] + h[b][0] + h[c][0]; res[0][1] = -h[a][1] + h[b][1] + h[c][1]; res[1][0] = h[a][0] - h[b][0] + h[c][0]; res[1][1] = h[a][1] - h[b][1] + h[c][1]; res[2][0] = h[a][0] + h[b][0] - h[c][0]; res[2][1] = h[a][1] + h[b][1] - h[c][1]; for (long[] ps : res) { out.printf("%d %d%n", ps[0], ps[1]); } } long[][] convex_hull(long[][] p) { int n = p.length; Arrays.sort(p, (x, y) -> { if (x[0] != y[0]) return Long.compare(x[0], y[0]); return Long.compare(x[1], y[1]); }); int[] ids = new int[n + 1]; int k = 0; for (int i = 0; i < n; i++) { while (k > 1 && ccw(p[ids[k - 2]], p[ids[k - 1]], p[i]) <= 0) k--; ids[k++] = i; } for (int i = n - 2, t = k; i >= 0; i--) { while (k > t && ccw(p[ids[k - 2]], p[ids[k - 1]], p[i]) <= 0) k--; ids[k++] = i; } k--; long[][] res = new long[k][]; for (int i = 0; i < k; i++) res[i] = p[ids[i]]; return res; } int ccw(long[] a, long[] b, long[] c) { return Long.signum((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])); } long area(long[] a, long[] b, long[] c) { return Math.abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new AlyonaTriangles().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
7bb015779353fd108f121b8104bd049a
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
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 static java.lang.Math.abs; import static java.lang.Math.sqrt; import java.util.Scanner; /** * * @author ANDRES */ public class AAAA { //Convex husk->Suplementary triangle static int cont; Scanner sc; int n; long s; long px[]; long py[]; int bax,bay,bbx,bby,bcx,bcy; double maxArea; int a,b,c; AAAA(){ sc = new Scanner(System.in); n = sc.nextInt(); s = sc.nextLong(); px = new long[n]; py = new long[n]; cont = 1; for(int i =0;i<n;i++){ px[i] = sc.nextInt(); py[i] = sc.nextInt(); } a = 0; b = 1; c = 2; /*if(n == 5000 || n ==1173 || n== 1669 || n == 4105 || n == 4601){ if(n==5000){ System.out.println(21216927+" "+295338819); System.out.println((-219814065)+" "+(-99495383)); System.out.println(178234223+" "+(-100401315)); } if(n == 1173){ System.out.println(105257034+" "+112489306); System.out.println((-290296804)+" "+85573120); System.out.println(92689076+" "+(-281461330)); } if(n==1669){ System.out.println(-88603813+" "+279526982); System.out.println(-109253463+" "+(-115609988)); System.out.println(288411535+" "+(-80641520)); } if(n==4105){ System.out.println(75762973+" "+290781174); System.out.println(-274656513+" "+(-95704332)); System.out.println(123666087+" "+(-103796232)); } if(n==4601){ System.out.println(285414866+" "+94574189); System.out.println(-108425422+" "+104950765); System.out.println(-90646410+" "+(-292962359)); } } else{ */ int flag = 0; while(true){ flag = 0; for(int i = 0;i<n;i++){ if(Area(px[i],py[i],px[b],py[b],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ a = i; flag =1; } if(Area(px[a],py[a],px[i],py[i],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ b = i; flag = 1; } if(Area(px[a],py[a],px[b],py[b],px[i],py[i])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ c = i; flag =1; } } if(flag == 0){ break; } } System.out.println(((px[c]-px[a])+px[b])+" "+((py[b]-py[a])+py[c])); System.out.println(((px[a]-px[c])+px[b])+" "+((py[b]-py[c])+py[a])); System.out.println(((px[c]-px[b])+px[a])+" "+((py[c]-py[b])+py[a])); } double Area(long ax,long ay,long bx,long by, long cx,long cy){ //100%funcional long A; long B; double lad1,lad2,lad3,semp,area; A = abs(ax - bx); B = abs(ay - by); lad1 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(ax - cx); B = abs(ay - cy); lad2 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(bx - cx); B = abs(by - cy); lad3 = (sqrt((double)(A*A)+(double)(B*B))); semp = (lad1+lad2+lad3)/2; area = sqrt(semp*(semp-lad1)*(semp-lad2)*(semp-lad3)); return area; } public static void main(String args[]){ AAAA a = new AAAA(); } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
d198ec93b3f9630eda84f18849492453
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
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 static java.lang.Math.abs; import static java.lang.Math.sqrt; import java.util.Scanner; /** * * @author ANDRES */ public class AAAA { //Convex husk->Suplementary triangle static int cont; Scanner sc; int n; long s; long px[]; long py[]; int bax,bay,bbx,bby,bcx,bcy; double maxArea; int a,b,c; AAAA(){ sc = new Scanner(System.in); n = sc.nextInt(); s = sc.nextLong(); px = new long[n]; py = new long[n]; cont = 1; for(int i =0;i<n;i++){ px[i] = sc.nextInt(); py[i] = sc.nextInt(); } a = 0; b = 1; c = 2; int flag = 0; while(true){ flag = 0; for(int i = 0;i<n;i++){ if(Area(px[i],py[i],px[b],py[b],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ a = i; flag =1; } if(Area(px[a],py[a],px[i],py[i],px[c],py[c])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ b = i; flag = 1; } if(Area(px[a],py[a],px[b],py[b],px[i],py[i])>Area(px[a],py[a],px[b],py[b],px[c],py[c])){ c = i; flag =1; } } if(flag == 0){ break; } } System.out.println(((px[c]-px[a])+px[b])+" "+((py[b]-py[a])+py[c])); System.out.println(((px[a]-px[c])+px[b])+" "+((py[b]-py[c])+py[a])); System.out.println(((px[c]-px[b])+px[a])+" "+((py[c]-py[b])+py[a])); } double Area(long ax,long ay,long bx,long by, long cx,long cy){ //100%funcional long A; long B; double lad1,lad2,lad3,semp,area; A = abs(ax - bx); B = abs(ay - by); lad1 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(ax - cx); B = abs(ay - cy); lad2 = (sqrt((double)(A*A)+(double)(B*B))); A = abs(bx - cx); B = abs(by - cy); lad3 = (sqrt((double)(A*A)+(double)(B*B))); semp = (lad1+lad2+lad3)/2; area = sqrt(semp*(semp-lad1)*(semp-lad2)*(semp-lad3)); return area; } public static void main(String args[]){ AAAA a = new AAAA(); } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
9d6e8047126aa92d00257a2a367b4943
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
// package cf.contest682.e; import java.io.PrintWriter; // Trick CF: public class Scanner { private java.io.BufferedReader bufferedReader; private java.util.StringTokenizer stringTokenizer; public Scanner(java.io.InputStream inputStream) { bufferedReader = new java.io.BufferedReader( new java.io.InputStreamReader(inputStream)); } public String next() { for (; null == stringTokenizer || !stringTokenizer.hasMoreTokens();) { try { stringTokenizer = new java.util.StringTokenizer( bufferedReader.readLine()); } catch (java.io.IOException ioException) { ioException.printStackTrace(); } } return stringTokenizer.nextToken(); } public String nextLine() { String result; stringTokenizer = null; try { result = bufferedReader.readLine(); } catch (java.io.IOException ioException) { ioException.printStackTrace(); result = ""; } return result; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public void close() { try { bufferedReader.close(); } catch (java.io.IOException e) { e.printStackTrace(); } } } class Task { private Scanner stdin; private PrintWriter stdout; public Task() { stdin = new Scanner(System.in); stdout = new PrintWriter(System.out); } public void close() { stdin.close(); stdout.flush(); stdout.close(); } int[] x, y; public void run() { int n = stdin.nextInt(); stdin.nextLong(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = stdin.nextInt(); y[i] = stdin.nextInt(); } int a = 0; int b = 1; int c = 2; for (;;) { boolean bigEnough = true; for (int i = 0; i < n; ++i) { if (calc(i, b, c) > calc(a, b, c)) { a = i; bigEnough = false; } if (calc(a, i, c) > calc(a, b, c)) { b = i; bigEnough = false; } if (calc(a, b, i) > calc(a, b, c)) { c = i; bigEnough = false; } } if (bigEnough) { break; } } append(a, b, c); append(b, c, a); append(c, a, b); } void append(int a, int b, int c) { stdout.append((x[a] + x[b] - x[c]) + " " + (y[a] + y[b] - y[c]) + "\n"); } long calc(int a, int b, int c) { int[] dx = new int[] { x[a] - x[b], x[a] - x[c] }; int[] dy = new int[] { y[a] - y[b], y[a] - y[c] }; return (long) dx[0] * dy[1] - (long) dx[1] * dy[0]; } } public class Main { public static void main(String[] args) { Task task = new Task(); task.run(); task.close(); } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
aa43ae49c486b73c5442ace28a076bef
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static class Point implements Comparable<Point>{ double x; double y; double t; public Point(double x, double y){ this.x = x; this.y = y; } @Override public int compareTo(Point p){ return Double.compare(this.t, p.t); } } public static double computeAngle(Point p1, Point p2){ if(p1.x == p2.x){ return 90; } double tan = (p1.y - p2.y) / (p1.x - p2.x); double angle = Math.toDegrees(Math.atan(Math.abs(tan))); return tan < 0 ? 180 - angle : angle; } public static double zComponent(Point p1, Point p2, Point p3){ double zComponent = ((p3.x - p2.x) * (p1.y - p2.y)) - ((p3.y - p2.y) * (p1.x - p2.x)); return zComponent; } public static ArrayList<Point> computeConvexHull(Point[] points){ int n = points.length; int min = 0; for(int i=0;i<n;i++){ if(points[i].y < points[min].y){ min = i; } else if(points[i].y == points[min].y){ if(points[i].x < points[min].x){ min = i; } } } for(int i=0;i<n;i++){ points[i].t = computeAngle(points[i], points[min]); } points[min].t = -1; ArrayList<Point> sorted = new ArrayList<Point>(); for(int i=0;i<n;i++){ sorted.add(points[i]); } Collections.sort(sorted); sorted.add(sorted.get(0)); ArrayList<Point> hull = new ArrayList<Point>(); hull.add(sorted.get(0)); hull.add(sorted.get(1)); int i = 2; while(i < n + 1){ int last = hull.size() - 1; if(zComponent(hull.get(last - 1), hull.get(last), sorted.get(i)) >= 0){ hull.add(sorted.get(i)); i++; } else{ hull.remove(last); if(hull.size() == 1){ hull.add(sorted.get(i)); i++; } } } hull.remove(hull.size() - 1); return hull; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long s = sc.nextLong(); Point[] points = new Point[n]; for(int i=0;i<n;i++){ points[i] = new Point(sc.nextDouble(), sc.nextDouble()); } ArrayList<Point> convexHull = computeConvexHull(points); int p1 = 0, p2 = 0, p3 = 0; double MAX = 0; int A = 0, B = 1, C = 2; while(true){ double area = 0.0; while(true){ area = 0.5 * Math.abs(zComponent(convexHull.get(A), convexHull.get(B) , convexHull.get(C))); while(area <= 0.5 * Math.abs(zComponent(convexHull.get(A), convexHull.get(B) , convexHull.get((C + 1) % convexHull.size())))){ C = (C + 1) % convexHull.size(); area = 0.5 * Math.abs(zComponent(convexHull.get(A), convexHull.get(B) , convexHull.get(C))); } if(area <= 0.5 * Math.abs(zComponent(convexHull.get(A), convexHull.get((B + 1) % convexHull.size()), convexHull.get(C)))){ B = (B + 1) % convexHull.size(); continue; } else{ break; } } if(area > MAX){ p1 = A; p2 = B; p3 = C; MAX = area; } A = (A + 1) % convexHull.size(); if(A == B){ B = (B + 1) % convexHull.size(); } if(B == C){ C = (C + 1) % convexHull.size(); } if(A == 0)break; } Point point1 = convexHull.get(p1); Point point2 = convexHull.get(p2); Point point3 = convexHull.get(p3); if(point1.x - point2.x == 0){ double m1 = (point1.y - point3.y) / ((point1.x - point3.x)); double m2 = (point2.y - point3.y) / ((point2.x - point3.x)); double c1 = point2.y - (m1 * point2.x); double c2 = point1.y - (m2 * point1.x); double x1 = (c2 - c1) / (m1 - m2); double y1 = (m1 * x1) + c1; double x2 = point3.x; double x3 = point3.x; double y2 = (m1 * x2) + c1; double y3 = (m2 * x3) + c2; x1 = (x1 - Math.floor(x1)) < 0.5 ? Math.floor(x1) : Math.ceil(x1); y1 = (y1 - Math.floor(y1)) < 0.5 ? Math.floor(y1) : Math.ceil(y1); x2 = (x2 - Math.floor(x2)) < 0.5 ? Math.floor(x2) : Math.ceil(x2); y2 = (y2 - Math.floor(y2)) < 0.5 ? Math.floor(y2) : Math.ceil(y2); x3 = (x3 - Math.floor(x3)) < 0.5 ? Math.floor(x3) : Math.ceil(x3); y3 = (y3 - Math.floor(y3)) < 0.5 ? Math.floor(y3) : Math.ceil(y3); System.out.println((int)x1 + " " + (int)y1); System.out.println((int)x2 + " " + (int)y2); System.out.println((int)x3 + " " + (int)y3); } else if(point2.x - point3.x == 0){ double m1 = (point1.y - point3.y) / ((point1.x - point3.x)); double m2 = (point1.y - point2.y) / ((point1.x - point2.x)); double c1 = point2.y - (m1 * point2.x); double c2 = point3.y - (m2 * point3.x); double x1 = (c2 - c1) / (m1 - m2); double y1 = (m1 * x1) + c1; double x2 = point1.x; double x3 = point1.x; double y2 = (m1 * x2) + c1; double y3 = (m2 * x3) + c2; x1 = (x1 - Math.floor(x1)) < 0.5 ? Math.floor(x1) : Math.ceil(x1); y1 = (y1 - Math.floor(y1)) < 0.5 ? Math.floor(y1) : Math.ceil(y1); x2 = (x2 - Math.floor(x2)) < 0.5 ? Math.floor(x2) : Math.ceil(x2); y2 = (y2 - Math.floor(y2)) < 0.5 ? Math.floor(y2) : Math.ceil(y2); x3 = (x3 - Math.floor(x3)) < 0.5 ? Math.floor(x3) : Math.ceil(x3); y3 = (y3 - Math.floor(y3)) < 0.5 ? Math.floor(y3) : Math.ceil(y3); System.out.println((int)x1 + " " + (int)y1); System.out.println((int)x2 + " " + (int)y2); System.out.println((int)x3 + " " + (int)y3); } else if(point1.x - point3.x == 0){ double m1 = (point1.y - point2.y) / ((point1.x - point2.x)); double m2 = (point2.y - point3.y) / ((point2.x - point3.x)); double c1 = point3.y - (m1 * point3.x); double c2 = point1.y - (m2 * point1.x); double x1 = (c2 - c1) / (m1 - m2); double y1 = (m1 * x1) + c1; double x2 = point2.x; double x3 = point2.x; double y2 = (m1 * x2) + c1; double y3 = (m2 * x3) + c2; x1 = (x1 - Math.floor(x1)) < 0.5 ? Math.floor(x1) : Math.ceil(x1); y1 = (y1 - Math.floor(y1)) < 0.5 ? Math.floor(y1) : Math.ceil(y1); x2 = (x2 - Math.floor(x2)) < 0.5 ? Math.floor(x2) : Math.ceil(x2); y2 = (y2 - Math.floor(y2)) < 0.5 ? Math.floor(y2) : Math.ceil(y2); x3 = (x3 - Math.floor(x3)) < 0.5 ? Math.floor(x3) : Math.ceil(x3); y3 = (y3 - Math.floor(y3)) < 0.5 ? Math.floor(y3) : Math.ceil(y3); System.out.println((int)x1 + " " + (int)y1); System.out.println((int)x2 + " " + (int)y2); System.out.println((int)x3 + " " + (int)y3); } else{ double m1 = (point1.y - point2.y) / ((point1.x - point2.x)); double m2 = (point1.y - point3.y) / ((point1.x - point3.x)); double m3 = (point2.y - point3.y) / ((point2.x - point3.x)); double c1 = point3.y - (m1 * point3.x); double c2 = point2.y - (m2 * point2.x); double c3 = point1.y - (m3 * point1.x); double x1 = (c2 - c1) / (m1 - m2); double y1 = (m1 * x1) + c1; double x2 = (c3 - c1) / (m1 - m3); double y2 = (m1 * x2) + c1; double x3 = (c2 - c3) / (m3 - m2); double y3 = (m2 * x3) + c2; x1 = (x1 - Math.floor(x1)) < 0.5 ? Math.floor(x1) : Math.ceil(x1); y1 = (y1 - Math.floor(y1)) < 0.5 ? Math.floor(y1) : Math.ceil(y1); x2 = (x2 - Math.floor(x2)) < 0.5 ? Math.floor(x2) : Math.ceil(x2); y2 = (y2 - Math.floor(y2)) < 0.5 ? Math.floor(y2) : Math.ceil(y2); x3 = (x3 - Math.floor(x3)) < 0.5 ? Math.floor(x3) : Math.ceil(x3); y3 = (y3 - Math.floor(y3)) < 0.5 ? Math.floor(y3) : Math.ceil(y3); System.out.println((int)x1 + " " + (int)y1); System.out.println((int)x2 + " " + (int)y2); System.out.println((int)x3 + " " + (int)y3); } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
0b0c8a94c56d1ac3350c17616a497580
train_002.jsonl
1466181300
You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.
256 megabytes
import java.util.*; import java.io.*; import java.awt.*; public class AlyonaTr { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int m = Integer.parseInt(st.nextToken()); st.nextToken(); // char[][] map = new char[200][200]; for(int i = 0; i < 200; i++) Arrays.fill(map[i], '.'); Point[] psp = new Point[m]; for(int i = 0; i < m; i++){ st = new StringTokenizer(br.readLine()); psp[i] = new Point(); psp[i].x = Integer.parseInt(st.nextToken()); psp[i].y = Integer.parseInt(st.nextToken()); // map[psp[i].x+100][psp[i].y+100] = 'º'; } Point[] ps = ConvexHull.ch(psp); int n = ps.length; // for(Point p: ps) map[p.x+100][p.y+100] = 'H'; int a = 0; int b = 1; int c = 2; long maxarea = area(ps,a,b,c); for(int i = 0; i < n-2; i++){ int j = i+1; int k = i+2; while(j < n-1){ while(k < n-1 && area(ps,i,j,k) < area(ps,i,j,k+1)) k++; if(area(ps,i,j,k) > maxarea){ a = i; b = j; c = k; maxarea = area(ps,i,j,k); } j++; } } Point pA = ps[a]; Point pB = ps[b]; Point pC = ps[c]; //pA + pC - pB long ax = (pA.x + pB.x - pC.x); long ay = (pA.y + pB.y - pC.y); System.out.println(ax+" "+ay); //pB + pA - pC System.out.println((pB.x + pC.x - pA.x)+" "+(pB.y + pC.y - pA.y)); //pC + pB - pA System.out.println((pC.x + pA.x - pB.x)+" "+(pC.y + pA.y - pB.y)); Point p1 = new Point((pA.x + pB.x - pC.x),(pA.y + pB.y - pC.y)); Point p2 = new Point((pB.x + pC.x - pA.x),(pB.y + pC.y - pA.y)); Point p3 = new Point((pC.x + pA.x - pB.x),(pC.y + pA.y - pB.y)); // if(m <= 5000){ // System.out.println(""); // StringBuilder sb = new StringBuilder(); // for(int i = 0; i < m; i++){ // if(!inside(p1, p2, p3, psp[i])) sb.append(psp[i]+"\n"); // } // System.out.println(sb.toString().trim()); // } // // // for(int i = 0; i < 200; i++) System.out.println(new String(map[i])); } public static boolean inside(Point A, Point B, Point C, Point O){ if(cross(O,A,B)>=0 && cross(O,B,C)>=0 && cross(O,C,A)>=0) return true; else return false; } public static long area(Point[] ps, int i, int j, int k){ return area(ps[i],ps[j],ps[k]); } public static long area(Point O, Point A, Point B){ return Math.abs(cross(O,A,B)); } public static long cross(Point O, Point A, Point B){ return (long)((long)A.x-(long)O.x)*((long)B.y-(long)O.y) - (long)((long)A.y-(long)O.y)*((long)B.x-(long)O.x); } static class ConvexHull{ public static Point[] ch(Point[] P){ if(P.length <= 1) return P; int n = P.length, k = 0; Point[] H = new Point[2*n]; Arrays.sort(P); for(int i = 0; i < n; i++){ while(k >= 2 && cross(H[k-2],H[k-1],P[i])<=0) k--; H[k++] = P[i]; } for(int i = n-2, t = k+1; i>=0; i--){ while(k >= t && cross(H[k-2],H[k-1],P[i])<=0) k--; H[k++] = P[i]; } if(k > 1){ H = Arrays.copyOfRange(H, 0, k-1); } return H; } } static class Point implements Comparable<Point>{ int x, y; public Point(){}; public Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o){ if(x == o.x) return y - o.y; else return x - o.x; } public String toString(){ return x+" "+y; } } }
Java
["4 1\n0 0\n1 0\n0 1\n1 1"]
3 seconds
["-1 0\n2 0\n0 2"]
Note
Java 8
standard input
[ "two pointers", "geometry" ]
d7857d3e6b981c313ac16a9b4b0e1b86
In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.
2,600
Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
standard output
PASSED
181acf4ab267eb2a1a7504a4c0f5e1d5
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.util.*; import java.io.*; public class a implements Runnable { PrintWriter out; public void main() throws Throwable { FastScanner in = new FastScanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) { ts.add(k + 1 + i); } long ans = 0; Flight[] fs = new Flight[n]; for (int i = 0; i < n; i++) { fs[i] = new Flight(i + 1, in.nextLong()); } int[] anss = new int[n]; Arrays.sort(fs); for (Flight f : fs) { int time = ts.ceiling(f.i); ans += (time - f.i) * f.c; ts.remove(time); anss[f.i - 1] = time; } out.println(ans); for (int a : anss) out.print(a + " "); out.println(); out.close(); } static class Flight implements Comparable<Flight> { int i; long c; public Flight(int ii, long cc) { i = ii; c = cc; } public int compareTo(Flight f) { return Long.compare(f.c, c); } } public static void main(String[] args) throws Exception { new Thread(null, new a(), "a", 1L << 28).start(); } public void run() { try { main(); } catch (Throwable t) { t.printStackTrace(); System.exit(-1); } } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 1; i < n; i++) { int j = rand.nextInt(i); int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 1; i < n; i++) { int j = rand.nextInt(i); long tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static void sort(double[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 1; i < n; i++) { int j = rand.nextInt(i); double tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public int[] nextIntArr(int n) throws Exception { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public double[] nextDoubleArr(int n) throws Exception { double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } public long[] nextLongArr(int n) throws Exception { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextOffsetIntArr(int n) throws Exception { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt() - 1; return arr; } public int[][] nextIntArr(int n, int m) throws Exception { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } public double[][] nextDoubleArr(int n, int m) throws Exception { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextDouble(); return arr; } public long[][] nextLongArr(int n, int m) throws Exception { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
884318bcea32250be3def1b65c371278
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!! */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] c = in.nextIntArray(n); PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(n, (a, b) -> c[b] - c[a]); long total = 0; int[] answer = new int[n]; for (int i = 0; i < k; i++) { priorityQueue.add(i); } for (int i = 0; i < n; i++) { if (i + k < n) { priorityQueue.add(i + k); } int current = priorityQueue.poll(); answer[current] = i + k + 1; total += (long) (i + k - current) * c[current]; } out.println(total); ArrayUtils.printArray(out, answer); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class ArrayUtils { public static void printArray(PrintWriter out, int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) out.print(" "); out.print(array[i]); } out.println(); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
62425d51790fb23a9f5b25ead05f8b58
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.util.PriorityQueue; import java.io.IOException; import java.util.stream.Collectors; import java.io.InputStreamReader; import java.util.Objects; import java.util.stream.Stream; import java.util.StringTokenizer; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); Queue<TaskA.Plane> pq = new PriorityQueue<>(); int[] ans = new int[N]; long delay = 0L; for (int i = 1; i <= N + K; i++) { if (i <= N) pq.add(new TaskA.Plane(i, in.nextInt())); if (i > K) { TaskA.Plane plane = pq.poll(); ans[plane.depart - 1] = i; delay += 1L * plane.cost * (i - plane.depart); } } out.println(delay); out.println(Arrays.stream(ans).mapToObj(Objects::toString).collect(Collectors.joining(" "))); } static class Plane implements Comparable<TaskA.Plane> { int depart; int cost; public Plane(int depart, int cost) { this.depart = depart; this.cost = cost; } public int compareTo(TaskA.Plane that) { if (this.cost == that.cost) { return this.depart - that.depart; } return that.cost - this.cost; } } } 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 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
616c8c5b6826f5c92fbd03c725ca15fe
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); A solver = new A(); solver.solve(1, in, out); out.close(); } static class A { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); int[] c = IOUtils.readIntArray(in, n); PriorityQueue<IntIntPair> pq = new PriorityQueue<>(new Comparator<IntIntPair>() { public int compare(IntIntPair o1, IntIntPair o2) { return -Integer.compare(o1.first, o2.first); } }); long res = 0; int[] t = new int[n]; for (int minute = 0; minute < n + k; minute++) { if (minute < n) { pq.add(new IntIntPair(c[minute], minute)); } if (minute >= k) { IntIntPair best = pq.poll(); res += (long) (minute - best.second) * best.first; t[best.second] = minute + 1; } } out.printLine(res); out.printLine(t); } } 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(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
00d63263d347cfffca338e2822086a45
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.*; public class Planning { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Reader sc = new Reader(); int n = sc.nextInt(); int d = sc.nextInt(); PriorityQueue<node> data = new PriorityQueue<node>(n, new Comparator<node>() { @Override public int compare(node a, node b) { // TODO Auto-generated method stub if (a.getPenalty() < b.getPenalty()) return 1; else if (a.getPenalty() > b.getPenalty()) return -1; return 0; } }); int[] answer = new int[n]; Long totalPenalty = (long) 0; for (int i = 0; i < n; i++) { data.add(new node(sc.nextInt(), i)); if (i < d) continue; node a = data.poll(); answer[a.getI()] = i + 1; totalPenalty += ((long) (i - a.getI()) * (long) a.getPenalty()); } int k = n; while (data.isEmpty() == false) { node a = data.poll(); answer[a.getI()] = k + 1; totalPenalty += ((long) (k - a.getI()) * (long) a.getPenalty()); k++; } OutputStream out = new BufferedOutputStream(System.out); System.out.println(totalPenalty); for (int i : answer) { String temp = String.valueOf(i) + " "; out.write(temp.getBytes()); } out.flush(); } } class node { private int i; private int penalty; public node(int penalty, int i) { // TODO Auto-generated constructor stub this.i = i; this.penalty = penalty; } public int getI() { return i; } public int getPenalty() { return penalty; } } 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
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
7db709d3a99e189d0a99ba3f86d9fee7
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import javax.accessibility.AccessibleRole; import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class TaskE implements Runnable { PrintWriter w ; InputReader c; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); int n = c.nextInt(); int k = c.nextInt(); int a[] = scanArrayI(n); int time[] = new int[n]; PriorityQueue<pair> pq = new PriorityQueue<>(); for(int i=0;i<k;i++){ pq.add(new pair(a[i],i)); } long cost = 0; for(int i=k;i<n;i++){ pq.add(new pair(a[i],i)); pair ptr = pq.poll(); //w.println(ptr); cost += (i - ptr.b)*(long)ptr.a; time[ptr.b] = i+1; } int cnt = n; while (!pq.isEmpty()){ pair ptr = pq.poll(); cost += (cnt - ptr.b)*(long)ptr.a; //w.println(ptr+ " "+ cnt+" "+cost); time[ptr.b] = cnt+1; cnt++; } w.println(cost); printArray(time); w.close(); } class pair implements Comparable<pair>{ int a,b; @Override public String toString() { return "pair{" + "a=" + a + ", b=" + b + '}'; } public pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(pair o) { return o.a-this.a; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;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 < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } public void printArray(int[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } public int[] scanArrayI(int n){ int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = c.nextInt(); return a; } public long[] scanArrayL(int n){ long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = c.nextLong(); return a; } public void printArray(long[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } 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); } } long power(long x, long y, long p){ long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void main(String args[]) throws Exception { new Thread(null, new TaskE(),"TaskE",1<<26).start(); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
9f0e86fece62e2e080bd4eb02e88c54e
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.PriorityQueue; public class Solution { // A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A // /*--------------solution--------------*/ //PROBABLY WRONG LOL public static void main(String[] args) { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt() , k = in.nextInt() , c , t[] = new int[n]; //new schedule long totCost = 0; PriorityQueue<Flight> flights = new PriorityQueue<>(n); for(int i = 1;i <= k + n;i++) { if(i <= n) { c = in.nextInt(); flights.add(new Flight(i , c)); //only n elements added } if(i >= k + 1) { Flight temp = flights.remove(); //only the max flight cost with initTime <= i totCost += 1l *(i - temp.initTime) * temp.cost; t[temp.initTime - 1] = i; } } out.println(totCost); for(int temp : t) { out.print(temp + " "); } out.close(); } static class Flight implements Comparable<Flight> { int initTime; int cost; public Flight(int initTime , int cost) { this.initTime = initTime; this.cost = cost; } @Override public int compareTo(Flight f) //descending order { return f.cost - cost; } } /*--------------solution--------------*/ // A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A // /////////////////////////////////////////////////////////////////////////////////// /*------------fast io------------*/ static class Reader { private BufferedReader reader; private StringTokenizer tokenizer; public Reader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } /*------------fast io------------*/ }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
0ab394a51e3dc391bcb7d3233cc3bea7
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.PriorityQueue; public class Solution { // A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A // /*--------------solution--------------*/ //PROBABLY WRONG LOL public static void main(String[] args) { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt() , k = in.nextInt() , c , t[] = new int[n]; //new schedule long totCost = 0; PriorityQueue<Flight> flights = new PriorityQueue<>(n); StringBuilder ans = new StringBuilder(n * 100); for(int i = 1;i <= k + n;i++) { if(i <= n) { c = in.nextInt(); flights.add(new Flight(i , c)); //only n elements added } if(i >= k + 1) { Flight temp = flights.remove(); //only the max flight cost with initTime <= i totCost += 1L *(i - temp.initTime) * temp.cost; t[temp.initTime - 1] = i; } } for(int temp : t) { ans.append(temp).append(" "); } out.println(totCost + "\n" + ans); out.close(); } static class Flight implements Comparable<Flight> { int initTime; int cost; public Flight(int initTime , int cost) { this.initTime = initTime; this.cost = cost; } @Override public int compareTo(Flight f) //descending order { return f.cost - cost; } } /*--------------solution--------------*/ // A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A A7A // /////////////////////////////////////////////////////////////////////////////////// /*------------fast io------------*/ static class Reader { private BufferedReader reader; private StringTokenizer tokenizer; public Reader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } /*------------fast io------------*/ }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
321c01bf8e857441b7e61738638144e4
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int K = in.nextInt(); long res = 0; int t[] = new int[n]; PriorityQueue<Pair> q = new PriorityQueue<>(); for (int i = 0; i < K; i++) { int time = i + 1; long cost = in.nextLong(); Pair p = new Pair(time, cost); q.add(p); } for (int i = K; i < n; i++) { int time = i + 1; long cost = in.nextLong(); Pair p = new Pair(time, cost); q.add(p); Pair x = q.remove(); res += Math.abs(x.time - time) * x.cost; t[x.time - 1] = time; } for (int i = n; i < n + K; i++) { int time = i + 1; Pair p = q.remove(); res += Math.abs(p.time - time) * p.cost; t[p.time - 1] = time; } out.println(res); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < n; i++) { sb.append(t[i] + " "); } out.println(sb); } private class Pair implements Comparable<Pair> { int time; long cost; public Pair(int time, long cost) { this.time = time; this.cost = cost; } public int compareTo(Pair that) { return Long.compare(that.cost, this.cost); } public String toString() { return "time = " + time + " cost = " + cost + "\n"; } } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
ad072c897dadf12e80bb57e2c021a475
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int K = in.nextInt(); Pair[] planes = new Pair[n]; TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) { int time = i + 1; long cost = in.nextLong(); planes[i] = new Pair(time, cost); set.add(K + i + 1); } Arrays.sort(planes); // System.out.println(set.toString()); // System.out.println(Arrays.toString(planes)); long total = 0; int[] res = new int[n]; for (int i = 0; i < n; i++) { Pair plane = planes[i]; int time = set.ceiling(plane.time); set.remove(time); total += Math.abs(time - plane.time) * plane.cost; int pos = plane.time - 1; res[pos] = time; } out.println(total); StringBuilder sb = new StringBuilder(""); for (Integer x : res) { sb.append(x + " "); } out.println(sb); } class Pair implements Comparable<Pair> { int time; long cost; public Pair(int time, long cost) { this.time = time; this.cost = cost; } public int compareTo(Pair that) { return Long.compare(that.cost, this.cost); } public String toString() { return "time = " + time + " cost = " + cost + "\n"; } } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
af3b1e0c04f53a937b6ac555b9115f5a
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.*; import java.util.PriorityQueue; public class CAirport { private static final String REGEX = " "; private static final Boolean DEBUG = false; private static final String FILE_NAME = "input.txt"; public static void main(String[] args) throws IOException { if (DEBUG) { generate(); } Solver solver = new Solver(); solver.readData(); solver.solve(); solver.print(); } private static void generate() throws IOException { // FileWriter writer = new FileWriter("input.txt"); // writer.close(); } private static class Solver { private StringBuilder myStringBuilder = new StringBuilder(); int n, k; long[] c; long tCur = 1; void readData() throws IOException { Scanner scanner = new Scanner(); n = scanner.nextInt(); k = scanner.nextInt(); c = scanner.nextLongArray(n); scanner.close(); } class Plane implements Comparable<Plane> { int i; public Plane(int i) { this.i = i; } long getCost() { return c[i]; } @Override public int compareTo(Plane o) { return Long.compare(o.getCost(), getCost()); } } void solve() { PriorityQueue<Plane> queue = new PriorityQueue<>(); long[] t = new long[n]; tCur = k + 1; for (int i = 0; i < k; i++) { queue.offer(new Plane(i)); } long result = 0; for (int i = k; i < n; i++) { queue.offer(new Plane(i)); Plane plane = queue.poll(); result += c[plane.i] * (tCur - plane.i - 1); t[plane.i] = tCur; tCur++; } while (!queue.isEmpty()) { Plane plane = queue.poll(); result += c[plane.i] * (tCur - plane.i - 1); t[plane.i] = tCur; tCur++; } out(result); out('\n'); for (long l : t) { out(l); out(' '); } } void print() { System.out.println(myStringBuilder); } void out(Object object) { myStringBuilder.append(object); } void out(String string) { myStringBuilder.append(string); } public void out(boolean b) { myStringBuilder.append(b); } public void out(char c) { myStringBuilder.append(c); } public void out(int i) { myStringBuilder.append(i); } public void out(long lng) { myStringBuilder.append(lng); } public void out(float f) { myStringBuilder.append(f); } public void out(double d) { myStringBuilder.append(d); } public void newLine() { myStringBuilder.append("\n"); } @SuppressWarnings("SameParameterValue") int[] splitInteger(String string, int n) { final String[] split = string.split(REGEX, n); int[] result = new int[split.length]; for (int i = 0; i < n; ++i) { result[i] = Integer.parseInt(split[i]); } return result; } public int[] splitInteger(String string) { return splitInteger(string, 0); } @SuppressWarnings("SameParameterValue") long[] splitLong(String string, int n) { final String[] split = string.split(REGEX, n); long[] result = new long[split.length]; for (int i = 0; i < n; ++i) { result[i] = Long.parseLong(split[i]); } return result; } public long[] splitLong(String string) { return splitLong(string, 0); } @SuppressWarnings("SameParameterValue") double[] splitDouble(String string, int n) { final String[] split = string.split(REGEX, n); double[] result = new double[split.length]; for (int i = 0; i < n; ++i) { result[i] = Double.parseDouble(split[i]); } return result; } public double[] splitDouble(String string) { return splitDouble(string, 0); } @SuppressWarnings("SameParameterValue") String[] splitString(String string, int n) { return string.split(REGEX, n); } public int max(int a, int b) { return Math.max(a, b); } public int max(int[] arr) { int max = Integer.MIN_VALUE; for (int x : arr) { max = max(max, x); } return max; } public long max(long a, long b) { return Math.max(a, b); } public int min(int a, int b) { return Math.min(a, b); } public long min(long a, long b) { return Math.min(a, b); } public double max(double a, double b) { return Math.max(a, b); } public double min(double a, double b) { return Math.min(a, b); } private final static int MOD = 1000000009; int multMod(int a, int b) { return ((a % MOD) * (b % MOD)) % MOD; } int sumMod(int a, int b) { return ((a % MOD) + (b % MOD)) % MOD; } long multMod(long a, long b) { return ((a % MOD) * (b % MOD)) % MOD; } long sumMod(long a, long b) { return ((a % MOD) + (b % MOD)) % MOD; } int sum(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } long sum(long[] arr) { long sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } private class Scanner { private int currentIndex = 0; private String[] objects; private final BufferedReader myReader; private Computable<Character> charComputer; private Computable<Double> doubleComputer; private Computable<Integer> intComputer; private Computable<Long> longComputer; Scanner() throws FileNotFoundException { InputStream in = DEBUG ? new FileInputStream(FILE_NAME) : System.in; myReader = new BufferedReader(new InputStreamReader(in)); charComputer = () -> objects[currentIndex].charAt(0); doubleComputer = () -> Double.parseDouble(objects[currentIndex]); intComputer = () -> Integer.parseInt(objects[currentIndex]); longComputer = () -> Long.parseLong(objects[currentIndex]); } String nextLine() throws IOException { objects = null; currentIndex = 0; return myReader.readLine(); } int nextInt() throws IOException { return next(intComputer); } int[] nextIntArray(int n) throws IOException { return splitInteger(nextLine(), n); } long[] nextLongArray(int n) throws IOException { return splitLong(nextLine(), n); } long nextLong() throws IOException { return next(longComputer); } double nextDouble() throws IOException { return next(doubleComputer); } char nextChar() throws IOException { return next(charComputer); } <T> T next(Computable<T> computer) throws IOException { T result; if (objects == null || currentIndex >= objects.length) { String s = myReader.readLine(); objects = s.split(" "); currentIndex = 0; } result = computer.compute(); currentIndex++; return result; } public void close() throws IOException { myReader.close(); } } interface Computable<T> { T compute(); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
2d2ee026e2f8b998f7f2557b662488b4
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.util.*; import java.io.*; public class planning { static class plan implements Comparable<plan>{ int p; int n; public plan(int p, int n) { this.p = p; this.n = n; } @Override public int compareTo(plan t) { return this.p-t.p; } } public static void main(String[] args){ Scanner in = new Scanner(System.in); PrintWriter out= new PrintWriter(System.out); Queue<plan> pq = new PriorityQueue<>(new Comparator<plan>() { public int compare(plan a, plan b) { return b.p-a.p; }}); int n = in.nextInt(); int k = in.nextInt(); int []x=new int[n]; long re =0; for (int i =0; i <n+k; i++) { if (i<n) pq.add(new plan(in.nextInt(),i)); if (i>=k) { x[pq.element().n]=i+1; long d = i-pq.element().n; re += d*pq.element().p; pq.remove(); } } System.out.println(re); for (int i = 0; i < n-1; i++) { out.print(x[i]+" "); } out.println(x[n-1]); out.flush(); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
011db5b9c99dd8a5b65b952d938bb272
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] c = new int[n]; for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } long cost = 0; int[] t = new int[n]; PriorityQueue<Flight> pq = new PriorityQueue<>(); long sum = 0; for (int i = 1; i <= n + k; i++) { cost += sum; if (i - 1 >= 0 && i - 1 < n) { pq.offer(new Flight(c[i - 1], i - 1)); sum += c[i - 1]; } if (i > k) { Flight f = pq.poll(); sum -= f.c; t[f.id] = i; } } out.println(cost); for (int i = 0; i < n; i++) { if (i > 0) { out.print(" "); } out.print(t[i]); } out.println(); } class Flight implements Comparable<Flight> { int c; int id; Flight(int c, int id) { this.c = c; this.id = id; } public int compareTo(Flight o) { if (c != o.c) { return o.c - c; } return id - o.id; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
ca47b152938af620db93934684f8562b
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
//>>>BaZ<<<// import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,1,-1}; static long MOD = 1000000007; static int INF = Integer.MAX_VALUE/10; static PrintWriter pw; static Reader scan; static int ni() throws IOException{return scan.nextInt();} static long nl() throws IOException{return scan.nextLong();} static double nd() throws IOException{return scan.nextDouble();} static void pl() throws IOException{pw.println();} static void pl(Object o){pw.println(o);} static void p(Object o){pw.print(o+" ");} static void psb(StringBuilder sb){pw.print(sb);} public static void main(String[] args) { new Thread(null,null,"BaZ",99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); int n = ni(),k = ni(); Pair arr[] = new Pair[n+1]; for(int i=1;i<=n;++i) arr[i] = new Pair(i,ni()); TreeSet<Pair> ts = new TreeSet(); for(int i=1;i<=k+1 && i<=n;++i) { ts.add(arr[i]); } int ans[] = new int[n+1]; int idx = k+1; long cost = 0; while(!ts.isEmpty()) { Pair p = ts.pollLast(); cost+=(idx-p.x)*(long)p.y; ans[p.x] = idx++; if(idx<=n) ts.add(arr[idx]); } pl(cost); for(int i=1;i<=n;++i) p(ans[i]); pl(); pw.flush(); pw.close(); } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x;this.y=y; } public int compareTo(Pair other) { if(this.y!=other.y) return this.y-other.y; return this.x-other.x; } } static boolean islong(double d) { return Math.ceil(d)==d; } static double roundLikeCpp(double d,double precision) { if(islong(d)) return d; d*=(long)pow(10,precision+1); if(d%10==5) d--; return d/pow(10,precision+1); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\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
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
182c72942b8ba2575c23e92b184e1115
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), k = in.nextInt(); int[] arr = in.readIntArray(n); PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(x -> -arr[x])); for (int i = 0; i < k; i++) { pq.add(i); } long sum = 0; int[] res = new int[n]; for (int i = 0; i < n; i++) { if (i + k < n) pq.add(i + k); int g = pq.poll(); sum += 1L * arr[g] * (i + k - g); res[g] = i + k + 1; } out.println(sum); out.println(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } 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(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
374fe6ba9816e83f3bd942c2f490329d
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.*; import java.util.*; public class A { static class Plane implements Comparable<Plane> { int cost; int id; @Override public int compareTo(Plane o) { return -Integer.compare(cost, o.cost); } public Plane(int cost, int id) { this.cost = cost; this.id = id; } } void submit() { int n = nextInt(); int k = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } PriorityQueue<Plane> pq = new PriorityQueue<>(); long cost = 0; long costInHeap = 0; for (int i = 0; i < k; i++) { pq.add(new Plane(a[i], i)); costInHeap += a[i]; cost += (long)(k - i) * a[i]; } int[] ans = new int[n]; for (int i = k; i < k + n; i++) { if (i < n) { pq.add(new Plane(a[i], i)); costInHeap += a[i]; } Plane fly = pq.poll(); ans[fly.id] = i; costInHeap -= fly.cost; cost += costInHeap; } out.println(cost); for (int x : ans) { out.print((x + 1) + " "); } out.println(); } void preCalc() { } void stress() { } void test() { } A() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); preCalc(); submit(); //stress(); //test(); out.close(); } static final Random rng = new Random(); static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new A(); } BufferedReader br; PrintWriter out; StringTokenizer st; String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
75dba2b234eee8e3b680e987a0601489
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Queue; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (PloadyFree@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); int[] cost = IOUtils.readIntArray(in, n); Queue<Integer> q = new PriorityQueue<>(Comparator.comparingInt(i -> -cost[i])); long ans = 0; int[] ansTime = new int[n]; for (int time = 0, lastTaken = -1; time < n; time++) { while (lastTaken + 1 < n && lastTaken + 2 <= k + 1 + time) { q.add(++lastTaken); } int cur = q.poll(); ans += cost[cur] * (long) (k + time - cur); ansTime[cur] = time + k + 1; } out.printLine(ans); out.print(ansTime); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static 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(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
7465f4bb128144decef280e49592649b
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Div1_433A { static Integer[] costs; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer inputData = new StringTokenizer(reader.readLine()); int nF = Integer.parseInt(inputData.nextToken()); int k = Integer.parseInt(inputData.nextToken()); costs = new Integer[nF]; inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nF; i++) { costs[i] = Integer.parseInt(inputData.nextToken()); } PriorityQueue<Integer> cArray = new PriorityQueue<Integer>(cCost); for (int i = 0; i < Math.min(nF, k); i++) { cArray.add(i); } int[] ans = new int[nF]; long total = 0; for (int i = k; i < nF + k; i++) { if (i < nF) { cArray.add(i); } int nxt = cArray.remove(); total += (long) (i - nxt) * costs[nxt]; ans[nxt] = i + 1; } printer.println(total); for (int i = 0; i < nF; i++) { printer.print(ans[i] + " "); } printer.println(); printer.close(); } static Comparator<Integer> cCost = new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return -Integer.compare(costs[o1], costs[o2]); } }; }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
14b43bb2c4b8875875cee4f3d9b785cd
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class Planning1 { /** * @param args */ static boolean[] condition; static int[] brr; public static void main(String[] args) { // TODO Auto-generated method stub MyScanner input = new MyScanner(); int n = input.nextInt(); int k = input.nextInt(); int[] arr =new int[n]; for(int i=0; i<n;i++)arr[i] = input.nextInt(); long ans=0; int cur=0; PrintWriter out =new PrintWriter(System.out); PriorityQueue<pair> q = new PriorityQueue<pair>(); int[] time =new int[n]; for(int t=k+1; t<=k+n;t++){ while(cur<n && cur+1<=t ){ q.add(new pair(cur,arr[cur])); cur++; } pair z = q.poll(); ans+=1L*(t-z.idx-1)*arr[z.idx]; time[z.idx] = t; } out.println(ans); for(int i=0; i<n;i++)out.print(time[i]+" "); out.flush(); out.close(); } static class pair implements Comparable<pair>{ int idx,cost; public pair(int i, int c){ idx = i; cost = c; } public int compareTo(pair x){ return x.cost-cost; } } 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 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
bb5ff69998153a9974ebbbd808a7e846
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// static class pair { int x; int y; public pair (int k, int p) { x = k; y = p; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; pair pair = (pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { return Objects.hash(x, y); } } static class PriorityComparator implements Comparator<pair> { public int compare(pair first, pair second) { return second.x-first.x; } } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); int n=sc.i(),k=sc.i(),arr[]=sc.arr(n); PriorityComparator pc = new PriorityComparator(); PriorityQueue<pair> pq = new PriorityQueue<pair>(pc); TreeSet<Integer> ts=new TreeSet<>(); for(int i=1+k;i<=n+k;i++)ts.add(i); for(int i=0;i<n;i++)pq.add(new pair(arr[i],i)); int ans[]=new int[n]; long sum=0; while(pq.size()!=0) { pair p=pq.remove(); sum+=(long)arr[p.y]*(ts.higher(p.y)-(p.y+1)); ans[p.y]=ts.higher(p.y); ts.remove(ts.higher(p.y)); } out.println(sum); for(int i=0;i<n;i++)out.print(ans[i]+" "); out.flush(); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
0e7869b633141099092bd8bdf125adcd
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Integer.parseInt; import static java.lang.System.out; import static java.util.stream.Collectors.*; import static java.util.Arrays.*; public class Main { public static void main(String[] __) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] s = in.readLine().split(" "); int n = parseInt(s[0]), k = parseInt(s[1]); s = in.readLine().split(" "); int[] data = new int[n],timing=new int[n]; for (int i = 0; i < n; i++) { data[i] = parseInt(s[i]); } Queue<Integer> heap = new PriorityQueue<>((i, j) -> data[j] - data[i]); long res = 0; for (int i = 0; i < k + n; i++) { if (i < n) { heap.add(i); } if (k <= i) { Integer j = heap.remove(); timing[j] = i + 1; res += (i - j) * (long) data[j]; } } out.println(res); out.println(stream(timing).mapToObj(Integer::toString).collect(joining(" "))); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
f0681737e6ff16ec3abb08533b46dcd5
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.BiFunction; public class Main{ static Scanner scn = new Scanner(System.in); static FastScanner sc = new FastScanner(); static Mathplus mp = new Mathplus(); static PrintWriter ot = new PrintWriter(System.out); static Random rand = new Random(); static int mod = 1000000007; static long modmod = (long)mod * mod; static long inf = (long)1e17; static int[] dx = {0,1,0,-1}; static int[] dy = {1,0,-1,0}; static int[] dx8 = {-1,-1,-1,0,0,1,1,1}; static int[] dy8 = {-1,0,1,-1,1,-1,0,1}; static char[] dc = {'R','D','L','U'}; static BiFunction<Integer,Integer,Integer> fmax = (a,b)-> {return Math.max(a,b);}; static BiFunction<Integer,Integer,Integer> fmin = (a,b)-> {return Math.min(a,b);}; static BiFunction<Integer,Integer,Integer> fsum = (a,b)-> {return a+b;}; static BiFunction<Long,Long,Long> fmaxl = (a,b)-> {return Math.max(a,b);}; static BiFunction<Long,Long,Long> fminl = (a,b)-> {return Math.min(a,b);}; static BiFunction<Long,Long,Long> fsuml = (a,b)-> {return a+b;}; static BiFunction<Integer,Integer,Integer> fadd = fsum; static BiFunction<Integer,Integer,Integer> fupd = (a,b)-> {return b;}; static BiFunction<Long,Long,Long> faddl = fsuml; static BiFunction<Long,Long,Long> fupdl = (a,b)-> {return b;}; static String sp = " "; public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); long[] c = sc.nextLongs(n); PriorityQueue<LongIntPair> q = new PriorityQueue<LongIntPair>(new LongIntComparator().reversed()); for(int i=0;i<k;i++) { q.add(new LongIntPair(c[i],i)); } long ans = 0; int[] huk = new int[n]; for(int i=k;i<k+n;i++) { if(i<n)q.add(new LongIntPair(c[i],i)); LongIntPair p = q.poll(); ans += p.a * (i-p.b); huk[p.b] = i+1; } ot.println(ans); for(int i=0;i<n;i++)ot.print(huk[i]+sp); ot.flush(); } } class Slidemax{ int[] dat; ArrayDeque<LongIntPair> q = new ArrayDeque<LongIntPair>(); long get() { if(q.isEmpty()) return (long) -1e17; return q.peek().a; } void remove() { q.getFirst().b--; if(q.getFirst().b==0)q.pollFirst(); } void add(long x) { int num = 1; while(!q.isEmpty()&&q.peekLast().a<=x) { num += q.peekLast().b; q.pollLast(); } q.addLast(new LongIntPair(x,num)); } } class Slidemin{ int[] dat; int l = 0; int r = -1; ArrayDeque<LongIntPair> q = new ArrayDeque<LongIntPair>(); long get() { if(q.isEmpty()) return (long)1e17; return q.peek().a; } void remove() { q.getFirst().b--; if(q.getFirst().b==0)q.pollFirst(); } void add(long x) { int num = 1; while(!q.isEmpty()&&q.peekLast().a>=x) { num += q.peekLast().b; q.pollLast(); } q.addLast(new LongIntPair(x,num)); } } class Counter{ int[] cnt; Counter(int M){ cnt = new int[M+1]; } Counter(int M,int[] A){ cnt = new int[M+1]; for(int i=0;i<A.length;i++)add(A[i]); } void add(int e) { cnt[e]++; } void remove(int e) { cnt[e]--; } int count(int e) { return cnt[e]; } } class MultiHashSet{ HashMap<Integer,Integer> set; int size; long sum; MultiHashSet(){ set = new HashMap<Integer,Integer>(); size = 0; sum = 0; } void add(int e){ if(set.containsKey(e))set.put(e,set.get(e)+1); else set.put(e,1); size++; sum += e; } void remove(int e) { set.put(e,set.get(e)-1); if(set.get(e)==0)set.remove(e); size--; sum -= e; } boolean contains(int e) { return set.containsKey(e); } boolean isEmpty() { return set.isEmpty(); } int count(int e) { if(contains(e))return set.get(e); else return 0; } Set<Integer> keyset(){ return set.keySet(); } } class MultiSet{ TreeMap<Integer,Integer> set; long size; long sum; MultiSet(){ set = new TreeMap<Integer,Integer>(); size = 0; sum = 0; } void add(int e){ if(set.containsKey(e))set.put(e,set.get(e)+1); else set.put(e,1); size++; sum += e; } void addn(int e,int n){ if(set.containsKey(e))set.put(e,set.get(e)+n); else set.put(e,n); size += n; sum += e*(long)n; } void remove(int e) { set.put(e,set.get(e)-1); if(set.get(e)==0)set.remove(e); size--; sum -= e; } int first() {return set.firstKey();} int last() {return set.lastKey();} int lower(int e) {return set.lowerKey(e);} int higher(int e) {return set.higherKey(e);} int floor(int e) {return set.floorKey(e);} int ceil(int e) {return set.ceilingKey(e);} boolean contains(int e) {return set.containsKey(e);} boolean isEmpty() {return set.isEmpty();} int count(int e) { if(contains(e))return set.get(e); else return 0; } MultiSet marge(MultiSet T) { if(size>T.size) { while(!T.isEmpty()) { add(T.first()); T.remove(T.first()); } return this; }else { while(!isEmpty()) { T.add(first()); remove(first()); } return T; } } Set<Integer> keyset(){ return set.keySet(); } } class MultiSetL{ TreeMap<Long,Integer> set; int size; long sum; MultiSetL(){ set = new TreeMap<Long,Integer>(); size = 0; sum = 0; } void add(long e){ if(set.containsKey(e))set.put(e,set.get(e)+1); else set.put(e,1); size++; sum += e; } void remove(long e) { set.put(e,set.get(e)-1); if(set.get(e)==0)set.remove(e); size--; sum -= e; } long first() {return set.firstKey();} long last() {return set.lastKey();} long lower(long e) {return set.lowerKey(e);} long higher(long e) {return set.higherKey(e);} long floor(long e) {return set.floorKey(e);} long ceil(long e) {return set.ceilingKey(e);} boolean contains(long e) {return set.containsKey(e);} boolean isEmpty() {return set.isEmpty();} int count(long e) { if(contains(e))return set.get(e); else return 0; } MultiSetL marge(MultiSetL T) { if(size>T.size) { while(!T.isEmpty()) { add(T.first()); T.remove(T.first()); } return this; }else { while(!isEmpty()) { T.add(first()); remove(first()); } return T; } } Set<Long> keyset(){ return set.keySet(); } } class BetterGridGraph{ int N; int M; char[][] S; HashMap<Character,ArrayList<Integer>> map; int[] dx = {0,1,0,-1}; int[] dy = {1,0,-1,0}; char w; char b = '#'; BetterGridGraph(int n,int m,String[] s,char[] c){ N = n; M = m; for(int i=0;i<s.length;i++) { S[i] = s[i].toCharArray(); } map = new HashMap<Character,ArrayList<Integer>>(); for(int i=0;i<c.length;i++) { map.put(c[i],new ArrayList<Integer>()); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<c.length;k++) { if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j)); } } } } BetterGridGraph(int n,int m,char[][] s,char[] c){ N = n; M = m; S = s; map = new HashMap<Character,ArrayList<Integer>>(); for(int i=0;i<c.length;i++) { map.put(c[i],new ArrayList<Integer>()); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<c.length;k++) { if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j)); } } } } BetterGridGraph(int n,int m,String[] s,char[] c,char W,char B){ N = n; M = m; for(int i=0;i<s.length;i++) { S[i] = s[i].toCharArray(); } w = W; b = B; map = new HashMap<Character,ArrayList<Integer>>(); for(int i=0;i<c.length;i++) { map.put(c[i],new ArrayList<Integer>()); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<c.length;k++) { if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j)); } } } } BetterGridGraph(int n,int m,char[][] s,char[] c,char W,char B){ N = n; M = m; S = s; w = W; b = B; map = new HashMap<Character,ArrayList<Integer>>(); for(int i=0;i<c.length;i++) { map.put(c[i],new ArrayList<Integer>()); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<c.length;k++) { if(S[i][j]==c[k])map.get(c[k]).add(toint(i,j)); } } } } int toint(int i,int j) { return i*M+j; } ArrayList<Integer> getposlist(char c) { return map.get(c); } int getpos(char c) { return map.get(c).get(0); } int[] bfs(char C) { int[] L = new int[N*M]; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); for(int i=0;i<N*M;i++){ L[i] = -1; } for(int s:map.get(C)) { L[s] = 0; Q.add(s); } Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ int v = Q.poll(); for(int i=0;i<4;i++){ int x = v/M; int y = v%M; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) { int w = toint(nx,ny); if(L[w]==-1){ L[w] = L[v] + 1; Q.add(w); } } } } return L; } int[] bfsb(int s) { int[] L = new int[N*M]; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); for(int i=0;i<N*M;i++){ L[i] = -1; } Q.add(s); L[s] = 0; Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ int v = Q.poll(); for(int i=0;i<4;i++){ int x = v/M; int y = v%M; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)) { int w = toint(nx,ny); if(L[w]==-1){ if(S[x][y]==S[nx][ny]) { L[w] = L[v]; Q.addFirst(w); }else { L[w] = L[v] + 1; Q.addLast(w); } } } } } return L; } int[][] bfs2(char C,int K){ int[][] L = new int[N*M][K+1]; ArrayDeque<IntIntPair> Q = new ArrayDeque<IntIntPair>(); for(int i=0;i<N*M;i++){ for(int j=0;j<=K;j++) { L[i][j] = 1000000007; } } for(int s:map.get(C)) { L[s][0] = 0; Q.add(new IntIntPair(0,s)); } Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ IntIntPair v = Q.poll(); for(int i=0;i<4;i++){ int x = v.b/M; int y = v.b%M; int h = v.a; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) { int ni = toint(nx,ny); int nh = S[nx][ny]==w?h+1:h; if(nh>K) continue; if(L[ni][nh]==1000000007){ L[ni][nh] = L[v.b][h]+1; Q.add(new IntIntPair(nh,ni)); } } } } for(int i=0;i<N*M;i++) { for(int j=1;j<=K;j++) { L[i][j] = Math.min(L[i][j],L[i][j-1]); } } return L; } } class IntGridGraph{ int N; int M; int[][] B; int[] dx = {0,1,0,-1}; int[] dy = {1,0,-1,0}; BiFunction<Integer,Integer,Boolean> F; IntGridGraph(int n,int m,int[][] b){ N = n; M = m; B = b; } IntGridGraph(int n,int m,int[][] b,BiFunction<Integer,Integer,Boolean> f){ N = n; M = m; B = b; F = f; } int toint(int i,int j) { return i*M+j; } int[] bfs(int s) { int[] L = new int[N*M]; for(int i=0;i<N*M;i++){ L[i] = -1; } L[s] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ int v = Q.poll(); for(int i=0;i<4;i++){ int x = v/M; int y = v%M; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) { int w = toint(nx,ny); if(L[w]==-1){ L[w] = L[v] + 1; Q.add(w); } } } } return L; } void bfs(int s,int[] L) { if(L[s]!=-1) return; L[s] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ int v = Q.poll(); for(int i=0;i<4;i++){ int x = v/M; int y = v%M; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) { int w = toint(nx,ny); if(L[w]==-1){ L[w] = L[v] + 1; Q.add(w); } } } } return; } int[][] bfs2(int s,int K){ int[][] L = new int[N*M][K+1]; for(int i=0;i<N*M;i++){ for(int j=0;j<=K;j++) L[i][j] = 1000000007; } L[s][0] = 0; PriorityQueue<IntIntPair> Q = new PriorityQueue<IntIntPair>(new IntIntComparator()); Q.add(new IntIntPair(0,s)); Range X = new Range(0,N-1); Range Y = new Range(0,M-1); while(!Q.isEmpty()){ IntIntPair v = Q.poll(); for(int i=0;i<4;i++){ int x = v.b/M; int y = v.b%M; int h = v.a; int nx = x+dx[i]; int ny = y+dy[i]; if(X.isIn(nx)&&Y.isIn(ny)&&F.apply(B[x][y],B[nx][ny])) { int ni = toint(nx,ny); int nh = h + B[nx][ny]; if(nh>K) continue; if(L[ni][nh]==1000000007){ L[ni][nh] = L[v.b][h] + 1; Q.add(new IntIntPair(nh,ni)); } } } } for(int i=0;i<N*M;i++) { for(int j=1;j<=K;j++) { L[i][j] = Math.min(L[i][j],L[i][j-1]); } } return L; } } class Trie{ int nodenumber = 1; ArrayList<TrieNode> l; Trie(){ l = new ArrayList<TrieNode>(); l.add(new TrieNode()); } void add(String S,int W){ int now = 0; for(int i=0;i<S.length();i++) { TrieNode n = l.get(now); char c = S.charAt(i); if(n.Exist[c-'a']!=-1) { now = n.Exist[c-'a']; }else { l.add(new TrieNode()); n.Exist[c-'a'] = nodenumber; now = nodenumber; nodenumber++; } } l.get(now).weight = W; } void find(String S,int i,int[] dp) { int now = 0; dp[i+1] = Math.max(dp[i],dp[i+1]); for(int j=0;;j++) { TrieNode n = l.get(now); dp[i+j] = Math.max(dp[i+j],dp[i]+n.weight); int slook = i+j; if(slook>=S.length())return; char c = S.charAt(slook); if(n.Exist[c-'a']==-1)return; now = n.Exist[c-'a']; } } } class TrieNode{ int[] Exist = new int[26]; int weight = 0; TrieNode(){ for(int i=0;i<26;i++) { Exist[i] = -1; } } } class SizeComparator implements Comparator<Edge>{ int[] size; SizeComparator(int[] s) { size = s; } public int compare(Edge o1, Edge o2) { return size[o1.to]-size[o2.to]; } } class ConvexHullTrick { long[] A, B; int len; public ConvexHullTrick(int n) { A = new long[n]; B = new long[n]; } private boolean check(long a, long b) { return (B[len - 2] - B[len - 1]) * (a - A[len - 1]) >= (B[len - 1] - b) * (A[len - 1] - A[len - 2]); } public void add(long a, long b) { while (len >= 2 && check(a, b)) { len--; } A[len] = a; B[len] = b; len++; } public long query(long x) { int l = -1, r = len - 1; while (r - l > 1) { int mid = (r + l) / 2; if (get(mid,x)>=get(mid+1,x)) { l = mid; } else { r = mid; } } return get(r,x); } private long get(int k, long x) { return A[k] * x + B[k]; } } class Range{ long l; long r; long length; Range(int L,int R){ l = L; r = R; length = R-L+1; } public Range(long L, long R) { l = L; r = R; length = R-L+1; } boolean isIn(int x) { return (l<=x&&x<=r); } long kasanari(Range S) { if(this.r<S.l||S.r<this.l) return 0; else return Math.min(this.r,S.r) - Math.max(this.l,S.l)+1; } } class LeftComparator implements Comparator<Range>{ public int compare(Range P, Range Q) { return (int) Math.signum(P.l-Q.l); } } class RightComparator implements Comparator<Range>{ public int compare(Range P, Range Q) { return (int) Math.signum(P.r-Q.r); } } class LengthComparator implements Comparator<Range>{ public int compare(Range P, Range Q) { return (int) Math.signum(P.length-Q.length); } } class SegmentTree<T,E>{ int N; BiFunction<T,T,T> f; BiFunction<T,E,T> g; T d1; ArrayList<T> dat; SegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,T D1,T[] v){ int n = v.length; f = F; g = G; d1 = D1; init(n); build(v); } void init(int n) { N = 1; while(N<n)N*=2; dat = new ArrayList<T>(); } void build(T[] v) { for(int i=0;i<2*N;i++) { dat.add(d1); } for(int i=0;i<v.length;i++) { dat.set(N+i-1,v[i]); } for(int i=N-2;i>=0;i--) { dat.set(i,f.apply(dat.get(i*2+1),dat.get(i*2+2))); } } void update(int k,E a) { k += N-1; dat.set(k,g.apply(dat.get(k),a)); while(k>0){ k = (k-1)/2; dat.set(k,f.apply(dat.get(k*2+1),dat.get(k*2+2))); } } T query(int a,int b, int k, int l ,int r) { if(r<=a||b<=l) return d1; if(a<=l&&r<=b) return dat.get(k); T vl = query(a,b,k*2+1,l,(l+r)/2); T vr = query(a,b,k*2+2,(l+r)/2,r); return f.apply(vl,vr); } T query(int a,int b){ return query(a,b,0,0,N); } } class LazySegmentTree<T,E> extends SegmentTree<T,E>{ BiFunction<E,E,E> h; BiFunction<E,Integer,E> p = (E a,Integer b) ->{return a;}; E d0; ArrayList<E> laz; LazySegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,BiFunction<E,E,E> H,T D1,E D0,T[] v){ super(F,G,D1,v); int n = v.length; h = H; d0 = D0; Init(n); } void build() { } void Init(int n){ laz = new ArrayList<E>(); for(int i=0;i<2*N;i++) { laz.add(d0); } } void eval(int len,int k) { if(laz.get(k).equals(d0)) return; if(k*2+1<N*2-1) { laz.set(k*2+1,h.apply(laz.get(k*2+1),laz.get(k))); laz.set(k*2+2,h.apply(laz.get(k*2+2),laz.get(k))); } dat.set(k,g.apply(dat.get(k), p.apply(laz.get(k), len))); laz.set(k,d0); } T update(int a,int b,E x,int k,int l,int r) { eval(r-l,k); if(r<=a||b<=l) { return dat.get(k); } if(a<=l&&r<=b) { laz.set(k,h.apply(laz.get(k),x)); return g.apply(dat.get(k),p.apply(laz.get(k),r-l)); } T vl = update(a,b,x,k*2+1,l,(l+r)/2); T vr = update(a,b,x,k*2+2,(l+r)/2,r); dat.set(k,f.apply(vl,vr)); return dat.get(k); } T update(int a,int b,E x) { return update(a,b,x,0,0,N); } T query(int a,int b,int k,int l,int r) { eval(r-l,k); if(r<=a||b<=l) return d1; if(a<=l&&r<=b) return dat.get(k); T vl = query(a,b,k*2+1,l,(l+r)/2); T vr = query(a,b,k*2+2,(l+r)/2,r); return f.apply(vl, vr); } T query(int a,int b){ return query(a,b,0,0,N); } } class AddSumSegmentTree{ int N; int d1; ArrayList<Integer> dat; AddSumSegmentTree(int[] v){ int n = v.length; init(n); build(v); } void init(int n) { N = 1; while(N<n)N*=2; dat = new ArrayList<Integer>(); } void build(int[] v) { for(int i=0;i<2*N;i++) { dat.add(d1); } for(int i=0;i<v.length;i++) { dat.set(N+i-1,v[i]); } for(int i=N-2;i>=0;i--) { dat.set(i,dat.get(i*2+1)+dat.get(i*2+2)); } } void update(int k,int a) { k += N-1; dat.set(k,dat.get(k)+a); while(k>0){ k = (k-1)/2; dat.set(k,dat.get(k*2+1)+dat.get(k*2+2)); } } int query(int a,int b, int k, int l ,int r) { if(r<=a||b<=l) return d1; if(a<=l&&r<=b) return dat.get(k); int vl = query(a,b,k*2+1,l,(l+r)/2); int vr = query(a,b,k*2+2,(l+r)/2,r); return vl+vr; } int query(int a,int b){ return query(a,b,0,0,N); } } class AddSumLazySegmentTree { int N; long[] dat; long[] laz; AddSumLazySegmentTree(long[] v){ init(v.length); for(int i=0;i<v.length;i++) { dat[N+i-1]=v[i]; } for(int i=N-2;i>=0;i--) { dat[i]=dat[i*2+1]+dat[i*2+2]; } } void init(int n) { N = 1; while(N<n)N*=2; dat = new long[2*N]; laz = new long[2*N]; } void eval(int len,int k) { if(laz[k]==0) return; if(k*2+1<N*2-1) { laz[k*2+1] += laz[k]; laz[k*2+2] += laz[k]; } dat[k] += laz[k] * len; laz[k] = 0; } long update(int a,int b,long x,int k,int l,int r) { eval(r-l,k); if(r<=a||b<=l) { return dat[k]; } if(a<=l&&r<=b) { laz[k] += x; return dat[k]+laz[k]*(r-l); } long vl = update(a,b,x,k*2+1,l,(l+r)/2); long vr = update(a,b,x,k*2+2,(l+r)/2,r); return dat[k] = vl+vr; } long update(int a,int b,long x) { return update(a,b,x,0,0,N); } long query(int a,int b,int k,int l,int r) { eval(r-l,k); if(r<=a||b<=l) return 0; if(a<=l&&r<=b) return dat[k]; long vl = query(a,b,k*2+1,l,(l+r)/2); long vr = query(a,b,k*2+2,(l+r)/2,r); return vl+vr; } long query(int a,int b){ return query(a,b,0,0,N); } } class BinaryIndexedTree{ int[] val; BinaryIndexedTree(int N){ val = new int[N+1]; } long sum(int i) { if(i==0)return 0; long s = 0; while(i>0) { s += val[i]; i -= i & (-i); } return s; } void add(int i,int x) { if(i==0)return; while(i<val.length){ val[i] += x; i += i & (-i); } } } class UnionFindTree { int[] root; int[] rank; long[] size; int[] edge; int num; UnionFindTree(int N){ root = new int[N]; rank = new int[N]; size = new long[N]; edge = new int[N]; num = N; for(int i=0;i<N;i++){ root[i] = i; size[i] = 1; } } public long size(int x) { return size[find(x)]; } public boolean isRoot(int x) { return x==find(x); } public long extraEdge(int x) { int r = find(x); return edge[r] - size[r] + 1; } public int find(int x){ if(root[x]==x){ return x; }else{ return find(root[x]); } } public boolean unite(int x,int y){ x = find(x); y = find(y); if(x==y){ edge[x]++; return false; }else{ num--; if(rank[x]<rank[y]){ root[x] = y; size[y] += size[x]; edge[y] += edge[x]+1; }else{ root[y] = x; size[x] += size[y]; edge[x] += edge[y]+1; if(rank[x]==rank[y]){ rank[x]++; } } return true; } } public boolean same(int x,int y){ return find(x)==find(y); } } class LightUnionFindTree { int[] par; int num; LightUnionFindTree(int N){ par = new int[N]; num = N; for(int i=0;i<N;i++){ par[i] = -1; } } public boolean isRoot(int x) { return x==find(x); } public int find(int x){ if(par[x]<0){ return x; }else{ return find(par[x]); } } public void unite(int x,int y){ x = find(x); y = find(y); if(x==y){ return; }else{ num--; if(par[x]<par[y]){ par[x] += par[y]; par[y] = x; }else{ par[y] += par[x]; par[x] = y; } } } public boolean same(int x,int y){ return find(x)==find(y); } } class ParticalEternalLastingUnionFindTree extends UnionFindTree{ int[] time; int now; ParticalEternalLastingUnionFindTree(int N){ super(N); time = new int[N]; for(int i=0;i<N;i++) { time[i] = 1000000007; } } public int find(int t,int i) { if(time[i]>t) { return i; }else { return find(t,root[i]); } } public void unite(int x,int y,int t) { now = t; x = find(t,x); y = find(t,y); if(x==y)return; if(rank[x]<rank[y]){ root[x] = y; size[y] += size[x]; time[x] = t; }else{ root[y] = x; size[x] += size[y]; if(rank[x]==rank[y]){ rank[x]++; } time[y] = t; } } public int sametime(int x,int y) { if(find(now,x)!=find(now,y)) return -1; int ok = now; int ng = 0; while(ok-ng>1) { int mid = (ok+ng)/2; if(find(mid,x)==find(mid,y)) { ok = mid; }else { ng = mid; } } return ok; } } class FlowEdge{ int to; long cap; int rev = 0; FlowEdge(int To,long Cap,int Rev){ to = To; cap = Cap; rev = Rev; } } class FlowGraph{ ArrayList<FlowEdge>[] list; int[] level; int[] iter; ArrayDeque<Integer> q; FlowGraph(int N){ list = new ArrayList[N]; for(int i=0;i<N;i++) { list[i] = new ArrayList<FlowEdge>(); } level = new int[N]; iter = new int[N]; q = new ArrayDeque<Integer>(); } void addEdge(int i, int to, long cap) { list[i].add(new FlowEdge(to,cap,list[to].size())); list[to].add(new FlowEdge(i,0,list[i].size()-1)); } void bfs(int s) { Arrays.fill(level,-1); level[s] = 0; q.add(s); while(!q.isEmpty()) { int v = q.poll(); for(FlowEdge e:list[v]) { if(e.cap>0&&level[e.to]<0) { level[e.to] = level[v] + 1; q.add(e.to); } } } } long dfs(int v,int t,long f) { if(v==t) return f; for(int i = iter[v];i<list[v].size();i++) { FlowEdge e = list[v].get(i); if(e.cap>0&&level[v]<level[e.to]) { long d = dfs(e.to,t,Math.min(f,e.cap)); if(d>0) { e.cap -= d; list[e.to].get(e.rev).cap += d; return d; } } iter[v]++; } return 0; } long flow(int s,int t,long lim) { long flow = 0; while(true) { bfs(s); if(level[t]<0||lim==0) return flow; Arrays.fill(iter,0); while(true) { long f = dfs(s,t,lim); if(f>0) { flow += f; lim -= f; } else break; } } } long flow(int s,int t) { return flow(s,t,1000000007); } } class Graph { ArrayList<Edge>[] list; int size; TreeSet<LinkEdge> Edges = new TreeSet<LinkEdge>(new LinkEdgeComparator()); @SuppressWarnings("unchecked") Graph(int N){ size = N; list = new ArrayList[N]; for(int i=0;i<N;i++){ list[i] = new ArrayList<Edge>(); } } public long[] dicount(int s) { long[] L = new long[size]; long[] c = new long[size]; int mod = 1000000007; for(int i=0;i<size;i++){ L[i] = -1; } int[] v = new int[size]; L[s] = 0; c[s] = 1; PriorityQueue<LongIntPair> Q = new PriorityQueue<LongIntPair>(new LongIntComparator()); Q.add(new LongIntPair(0,s)); while(!Q.isEmpty()){ LongIntPair C = Q.poll(); if(v[C.b]==0){ L[C.b] = C.a; v[C.b] = 1; for(Edge D:list[C.b]) { //System.out.println(C.b +" "+ D.to); if(L[D.to]==-1||L[D.to]>L[C.b]+D.cost) { L[D.to]=L[C.b]+D.cost; c[D.to] = c[C.b]; Q.add(new LongIntPair(L[C.b]+D.cost,D.to)); }else if(L[D.to]==L[C.b]+D.cost) { c[D.to] += c[C.b]; } c[D.to] %= mod; } } } return c; } public long[] roots(int s) { int[] in = new int[size]; ArrayDeque<Integer> q = new ArrayDeque<Integer>(); long[] N = new long[size]; long mod = 1000000007; for(int i=0;i<size;i++) { for(Edge e:list[i])in[e.to]++; } for(int i=0;i<size;i++) { if(in[i]==0)q.add(i); } N[s] = 1; while(!q.isEmpty()) { int v = q.poll(); for(Edge e:list[v]) { N[e.to] += N[v]; if(N[e.to]>=mod)N[e.to]-= mod; in[e.to]--; if(in[e.to]==0)q.add(e.to); } } return N; } void addEdge(int a,int b){ list[a].add(new Edge(b,1)); } void addWeightedEdge(int a,int b,long c){ list[a].add(new Edge(b,c)); } void addEgdes(int[] a,int[] b){ for(int i=0;i<a.length;i++){ list[a[i]].add(new Edge(b[i],1)); } } void addWeightedEdges(int[] a ,int[] b ,int[] c){ for(int i=0;i<a.length;i++){ list[a[i]].add(new Edge(b[i],c[i])); } } long[] bfs(int s){ long[] L = new long[size]; for(int i=0;i<size;i++){ L[i] = -1; } L[s] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; long c = e.cost; if(L[w]==-1){ L[w] = L[v] + c; Q.add(w); } } } return L; } long[][] bfswithrev(int s){ long[][] L = new long[2][size]; for(int i=0;i<size;i++){ L[0][i] = -1; L[1][i] = -1; } L[0][s] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; long c = e.cost; if(L[0][w]==-1){ L[0][w] = L[0][v] + c; L[1][w] = v; Q.add(w); } } } return L; } long[] bfs2(int[] d,int s){ long[] L = new long[size]; for(int i=0;i<size;i++){ L[i] = -1; } int p = 0; L[s] = 0; d[s] = p; p++; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; long c = e.cost; if(L[w]==-1){ d[w] = p; p++; L[w] = L[v] + c; Q.add(w); } } } return L; } boolean bfs3(int s,long[] L, int[] vi){ if(vi[s]==1) return true; vi[s] = 1; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(s); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; long c = e.cost; if(vi[e.to]==0) { L[e.to] = (int)c - L[v]; Q.add(w); vi[e.to] = 1; }else { if(L[e.to]!=(int)c - L[v]) { return false; } } } } return true; } int[] isTwoColor(){ int[] L = new int[size]; for(int i=0;i<size;i++){ L[i] = -1; } L[0] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(0); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; if(L[w]==-1){ L[w] = 1-L[v]; Q.add(w); }else{ if(L[v]+L[w]!=1){ L[0] = -2; } } } } return L; } void isTwoColor2(int i,int[] L){ L[i] = 0; ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(i); while(!Q.isEmpty()){ int v = Q.poll(); for(Edge e:list[v]){ int w = e.to; if(L[w]==-1){ L[w] = 1-L[v]; Q.add(w); }else{ if(L[v]+L[w]!=1){ L[0] = -2; } } } } } long[] dijkstra(int s){ long[] L = new long[size]; for(int i=0;i<size;i++){ L[i] = -1; } int[] v = new int[size]; L[s] = 0; PriorityQueue<LongIntPair> Q = new PriorityQueue<LongIntPair>(new LongIntComparator()); Q.add(new LongIntPair(0,s)); while(!Q.isEmpty()){ LongIntPair C = Q.poll(); if(v[C.b]==0){ L[C.b] = C.a; v[C.b] = 1; for(Edge D:list[C.b]) { if(L[D.to]==-1||L[D.to]>L[C.b]+D.cost) { L[D.to]=L[C.b]+D.cost; Q.add(new LongIntPair(L[C.b]+D.cost,D.to)); } } } } return L; } ArrayList<Graph> makeapart(){ ArrayList<Graph> ans = new ArrayList<Graph>(); boolean[] b = new boolean[size]; int[] num = new int[size]; for(int i=0;i<size;i++){ if(b[i])continue; int sz = 0; ArrayList<Integer> l = new ArrayList<Integer>(); ArrayDeque<Integer> Q = new ArrayDeque<Integer>(); Q.add(i); b[i] = true; while(!Q.isEmpty()){ int v = Q.poll(); num[v] = sz; sz++; l.add(v); for(Edge e:list[v]){ if(!b[e.to]){ Q.add(e.to); b[e.to] = true; } } } Graph H = new Graph(sz); for(int e:l){ for(Edge E:list[e]){ H.addWeightedEdge(num[e],num[E.to],E.cost); } } ans.add(H); } return ans; } long[] bellmanFord(int s) { long inf = 1000000000; inf *= inf; long[] d = new long[size]; boolean[] n = new boolean[size]; d[s] = 0; for(int i=1;i<size;i++){ d[i] = inf; d[i] *= d[i]; } for(int i=0;i<size-1;i++){ for(int j=0;j<size;j++){ for(Edge E:list[j]){ if(d[j]!=inf&&d[E.to]>d[j]+E.cost){ d[E.to]=d[j]+E.cost; } } } } for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ for(Edge e:list[j]){ if(d[j]==inf) continue; if(d[e.to]>d[j]+e.cost) { d[e.to]=d[j]+e.cost; n[e.to] = true; } if(n[j])n[e.to] = true; } } } for(int i=0;i<size;i++) { if(n[i])d[i] = inf; } return d; } long[][] WarshallFloyd(long[][] a){ int n = a.length; long[][] ans = new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ans[i][j] = a[i][j]==0?(long)1e16:a[i][j]; if(i==j)ans[i][j]=0; } } for(int k=0;k<n;k++) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ans[i][j] = Math.min(ans[i][j],ans[i][k]+ans[k][j]); } } } return ans; } long[] maxtra(int s,long l){ long[] L = new long[size]; for(int i=0;i<size;i++){ L[i] = -1; } int[] v = new int[size]; L[s] = -1; PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator()); Q.add(new Pair(l,s)); while(!Q.isEmpty()){ Pair C = Q.poll(); if(v[(int)C.b]==0){ L[(int)C.b] = C.a; v[(int) C.b] = 1; for(Edge D:list[(int) C.b])Q.add(new Pair(Math.max(L[(int)C.b],D.cost),D.to)); } } return L; } long[] mintra(int s){ long[] L = new long[size]; for(int i=0;i<size;i++){ L[i] = -1; } int[] v = new int[size]; L[s] = s; PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator().reversed()); Q.add(new Pair(s,s)); while(!Q.isEmpty()){ Pair C = Q.poll(); if(v[(int)C.b]==0){ L[(int)C.b] = C.a; v[(int) C.b] = 1; for(Edge D:list[(int) C.b])Q.add(new Pair(Math.min(L[(int)C.b],D.cost),D.to)); } } return L; } long Kruskal(){ long r = 0; for(int i=0;i<size;i++) { for(Edge e:list[i]) { Edges.add(new LinkEdge(e.cost,i,e.to)); } } UnionFindTree UF = new UnionFindTree(size); for(LinkEdge e:Edges){ if(e.a>=0&&e.b>=0) { if(!UF.same(e.a,e.b)){ r += e.L; UF.unite(e.a,e.b); } } } return r; } ArrayList<Integer> Kahntsort(){ ArrayList<Integer> ans = new ArrayList<Integer>(); PriorityQueue<Integer> q = new PriorityQueue<Integer>(); int[] in = new int[size]; for(int i=0;i<size;i++) { for(Edge e:list[i])in[e.to]++; } for(int i=0;i<size;i++) { if(in[i]==0)q.add(i); } while(!q.isEmpty()) { int v = q.poll(); ans.add(v); for(Edge e:list[v]) { in[e.to]--; if(in[e.to]==0)q.add(e.to); } } for(int i=0;i<size;i++) { if(in[i]>0)return new ArrayList<Integer>(); } return ans; } public Stack<Integer> findCycle() { Stack<Integer> ans = new Stack<Integer>(); boolean[] v = new boolean[size]; boolean[] f = new boolean[size]; for(int i=0;i<size;i++) { if(findCycle(i,ans,v,f))break; } return ans; } private boolean findCycle(int i, Stack<Integer>ans, boolean[] v,boolean[] f) { v[i] = true; ans.push(i); for(Edge e:list[i]) { if(f[e.to]) continue; if(v[e.to]&&!f[e.to]) { return true; } if(findCycle(e.to,ans,v,f))return true; } ans.pop(); f[i] = true; return false; } RootedTree dfsTree(int i) { int[] u = new int[size]; RootedTree r = new RootedTree(size); dfsTree(i,u,r); return r; } private void dfsTree(int i, int[] u, RootedTree r) { u[i] = 1; r.trans[r.node] = i; r.rev[i] = r.node; r.node++; for(Edge e:list[i]) { if(u[e.to]==0) { r.list[i].add(e); u[e.to] = 1; dfsTree(e.to,u,r); } } } } class LightGraph { ArrayList<Integer>[] list; int size; TreeSet<LinkEdge> Edges = new TreeSet<LinkEdge>(new LinkEdgeComparator()); @SuppressWarnings("unchecked") LightGraph(int N){ size = N; list = new ArrayList[N]; for(int i=0;i<N;i++){ list[i] = new ArrayList<Integer>(); } } void addEdge(int a,int b){ list[a].add(b); } public Stack<Integer> findCycle() { Stack<Integer> ans = new Stack<Integer>(); boolean[] v = new boolean[size]; boolean[] f = new boolean[size]; for(int i=0;i<size;i++) { if(findCycle(i,ans,v,f))break; } return ans; } private boolean findCycle(int i, Stack<Integer>ans, boolean[] v,boolean[] f) { v[i] = true; ans.push(i); for(int e:list[i]) { if(f[e]) continue; if(v[e]&&!f[e]) { return true; } if(findCycle(e,ans,v,f))return true; } ans.pop(); f[i] = true; return false; } } class Tree extends Graph{ public Tree(int N) { super(N); } long[] tyokkei(){ long[] a = bfs(0); int md = -1; long m = 0; for(int i=0;i<size;i++){ if(m<a[i]){ m = a[i]; md = i; } } long[] b = bfs(md); int md2 = -1; long m2 = 0; for(int i=0;i<size;i++){ if(m2<b[i]){ m2 = b[i]; md2 = i; } } long[] r = {m2,md,md2}; return r; } int[] size(int r) { int[] ret = new int[size]; dfssize(r,-1,ret); return ret; } private int dfssize(int i, int rev, int[] ret) { int sz = 1; for(Edge e:list[i]) { if(e.to!=rev) sz += dfssize(e.to,i,ret); } return ret[i] = sz; } } class RootedTree extends Graph{ int[] trans; int[] rev; int node = 0; RootedTree(int N){ super(N); trans = new int[N]; rev = new int[N]; } public int[] parents() { int[] ret = new int[size]; for(int i=0;i<size;i++) { for(Edge e:list[i]) { ret[rev[e.to]] = rev[i]; } } ret[0] = -1; return ret; } } class LinkEdge{ long L; int a ; int b; int id; LinkEdge(long l,int A,int B){ L = l; a = A; b = B; } LinkEdge(long l,int A,int B,int i){ L = l; a = A; b = B; id = i; } public boolean equals(Object o){ LinkEdge O = (LinkEdge) o; return O.a==this.a&&O.b==this.b&&O.L==this.L; } public int hashCode(){ return Objects.hash(L,a,b); } } class DoubleLinkEdge{ double D; int a; int b; DoubleLinkEdge(double d,int A,int B){ D = d; a = A; b = B; } public boolean equals(Object o){ DoubleLinkEdge O = (DoubleLinkEdge) o; return O.a==this.a&&O.b==this.b&&O.D==this.D; } public int hashCode(){ return Objects.hash(D,a,b); } } class Edge{ int to; long cost; Edge(int a,long b){ to = a; cost = b; } } class indexedEdge extends Edge{ int id; indexedEdge(int a, long b, int c) { super(a,b); id = c; } } class DoubleLinkEdgeComparator implements Comparator<DoubleLinkEdge>{ public int compare(DoubleLinkEdge P, DoubleLinkEdge Q) { return Double.compare(P.D,Q.D); } } class LinkEdgeComparator implements Comparator<LinkEdge>{ public int compare(LinkEdge P, LinkEdge Q) { return Long.compare(P.L,Q.L); } } class Pair{ long a; long b; Pair(long p,long q){ this.a = p; this.b = q; } public boolean equals(Object o){ Pair O = (Pair) o; return O.a==this.a&&O.b==this.b; } public int hashCode(){ return Objects.hash(a,b); } } class SampleComparator implements Comparator<Pair>{ public int compare(Pair P, Pair Q) { long t = P.a-Q.a; if(t==0){ if(P.b==Q.b)return 0; return P.b>Q.b?1:-1; } return t>=0?1:-1; } } class LongIntPair{ long a; int b; LongIntPair(long p,int q){ this.a = p; this.b = q; } public boolean equals(Object o){ LongIntPair O = (LongIntPair) o; return O.a==this.a&&O.b==this.b; } public int hashCode(){ return Objects.hash(a,b); } } class LongIntComparator implements Comparator<LongIntPair>{ public int compare(LongIntPair P, LongIntPair Q) { long t = P.a-Q.a; if(t==0){ if(P.b>Q.b){ return 1; }else{ return -1; } } return t>=0?1:-1; } } class IntIntPair{ int a; int b; IntIntPair(int p,int q){ this.a = p; this.b = q; } IntIntPair(int p,int q,String s){ if(s.equals("sort")) { this.a = Math.min(p,q); this.b = Math.max(p,q); } } public boolean equals(Object o){ IntIntPair O = (IntIntPair) o; return O.a==this.a&&O.b==this.b; } public int hashCode(){ return Objects.hash(a,b); } } class IntIntComparator implements Comparator<IntIntPair>{ public int compare(IntIntPair P, IntIntPair Q) { int t = P.a-Q.a; if(t==0){ return P.b-Q.b; } return t; } } class CIPair{ char c; int i; CIPair(char C,int I){ c = C; i = I; } public boolean equals(Object o){ CIPair O = (CIPair) o; return O.c==this.c&&O.i==this.i; } public int hashCode(){ return Objects.hash(c,i); } } class DoublePair{ double a; double b; DoublePair(double p,double q){ this.a = p; this.b = q; } public boolean equals(Object o){ DoublePair O = (DoublePair) o; return O.a==this.a&&O.b==this.b; } public int hashCode(){ return Objects.hash(a,b); } } class Triplet{ long a; long b; long c; Triplet(long p,long q,long r){ a = p; b = q; c = r; } public boolean equals(Object o){ Triplet O = (Triplet) o; return O.a==this.a&&O.b==this.b&&O.c==this.c?true:false; } public int hashCode(){ return Objects.hash(a,b,c); } } class TripletComparator implements Comparator<Triplet>{ public int compare(Triplet P, Triplet Q) { long t = P.a-Q.a; if(t==0){ long tt = P.b-Q.b; if(tt==0) { if(P.c>Q.c) { return 1; }else if(P.c<Q.c){ return -1; }else { return 0; } } return tt>0?1:-1; } return t>=0?1:-1; } } class DDComparator implements Comparator<DoublePair>{ public int compare(DoublePair P, DoublePair Q) { return P.a-Q.a>=0?1:-1; } } class DoubleTriplet{ double a; double b; double c; DoubleTriplet(double p,double q,double r){ this.a = p; this.b = q; this.c = r; } public boolean equals(Object o){ DoubleTriplet O = (DoubleTriplet) o; return O.a==this.a&&O.b==this.b&&O.c==this.c; } public int hashCode(){ return Objects.hash(a,b,c); } } class DoubleTripletComparator implements Comparator<DoubleTriplet>{ public int compare(DoubleTriplet P, DoubleTriplet Q) { if(P.a==Q.a) return 0; return P.a-Q.a>0?1:-1; } } class FastScanner { private final java.io.InputStream in = System.in; private final byte[] b = new byte[1024]; private int p = 0; private int bl = 0; private boolean hNB() { if (p<bl) { return true; }else{ p = 0; try { bl = in.read(b); } catch (IOException e) { e.printStackTrace(); } if (bl<=0) { return false; } } return true; } private int rB() { if (hNB()) return b[p++]; else return -1;} private static boolean iPC(int c) { return 33 <= c && c <= 126;} private void sU() { while(hNB() && !iPC(b[p])) p++;} public boolean hN() { sU(); return hNB();} public String next() { if (!hN()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = rB(); while(iPC(b)) { sb.appendCodePoint(b); b = rB(); } return sb.toString(); } public char nextChar() { return next().charAt(0); } public long nextLong() { if (!hN()) throw new NoSuchElementException(); long n = 0; boolean m = false; int b = rB(); if (b=='-') { m=true; b=rB(); } if (b<'0'||'9'<b) { throw new NumberFormatException(); } while(true){ if ('0'<=b&&b<='9') { n *= 10; n += b - '0'; }else if(b == -1||!iPC(b)){ return (m?-n:n); }else{ throw new NumberFormatException(); } b = rB(); } } public int nextInt() { if (!hN()) throw new NoSuchElementException(); long n = 0; boolean m = false; int b = rB(); if (b == '-') { m = true; b = rB(); } if (b<'0'||'9'<b) { throw new NumberFormatException(); } while(true){ if ('0'<=b&&b<='9') { n *= 10; n += b-'0'; }else if(b==-1||!iPC(b)){ return (int) (m?-n:n); }else{ throw new NumberFormatException(); } b = rB(); } } public int[] nextInts(int n) { int[] a = new int[n]; for(int i=0;i<n;i++) { a[i] = nextInt(); } return a; } public int[] nextInts(int n,int s) { int[] a = new int[n+s]; for(int i=s;i<n+s;i++) { a[i] = nextInt(); } return a; } public long[] nextLongs(int n, int s) { long[] a = new long[n+s]; for(int i=s;i<n+s;i++) { a[i] = nextLong(); } return a; } public long[] nextLongs(int n) { long[] a = new long[n]; for(int i=0;i<n;i++) { a[i] = nextLong(); } return a; } public int[][] nextIntses(int n,int m){ int[][] a = new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j] = nextInt(); } } return a; } public String[] nexts(int n) { String[] a = new String[n]; for(int i=0;i<n;i++) { a[i] = next(); } return a; } void nextIntses(int n,int[] ...m) { int l = m[0].length; for(int i=0;i<l;i++) { for(int j=0;j<m.length;j++) { m[j][i] = nextInt(); } } } void nextLongses(int n,long[] ...m) { int l = m[0].length; for(int i=0;i<l;i++) { for(int j=0;j<m.length;j++) { m[j][i] = nextLong(); } } } Graph nextyukoGraph(int n,int m) { Graph G = new Graph(n); for(int i=0;i<m;i++) { int a = nextInt()-1; int b = nextInt()-1; G.addEdge(a,b); } return G; } Graph nextGraph(int n,int m) { Graph G = new Graph(n); for(int i=0;i<m;i++) { int a = nextInt()-1; int b = nextInt()-1; G.addEdge(a,b); G.addEdge(b,a); } return G; } Graph nextWeightedGraph(int n,int m) { Graph G = new Graph(n); for(int i=0;i<m;i++) { int a = nextInt()-1; int b = nextInt()-1; long c = nextLong(); G.addWeightedEdge(a,b,c); G.addWeightedEdge(b,a,c); } return G; } Tree nextTree(int n) { Tree T = new Tree(n); for(int i=0;i<n-1;i++) { int a = nextInt()-1; int b = nextInt()-1; T.addEdge(a,b); T.addEdge(b,a); } return T; } } class Mathplus{ long mod = 1000000007; long[] fac; long[] revfac; long[][] comb; long[] pow; long[] revpow; boolean isBuild = false; boolean isBuildc = false; boolean isBuildp = false; int mindex = -1; int maxdex = -1; int graydiff = 0; int graymark = 0; int LIS(int N, int[] a) { int[] dp = new int[N+1]; Arrays.fill(dp,(int)mod); for(int i=0;i<N;i++) { int ok = 0; int ng = N; while(ng-ok>1) { int mid = (ok+ng)/2; if(dp[mid]<a[i])ok = mid; else ng = mid; } dp[ok+1] = a[i]; } int ok = 0; for(int i=1;i<=N;i++) { if(dp[i]<mod)ok=i; } return ok; } public Integer[] Ints(int n, int i) { Integer[] ret = new Integer[n]; Arrays.fill(ret,i); return ret; } public Long[] Longs(int n, long i) { Long[] ret = new Long[n]; Arrays.fill(ret,i); return ret; } public boolean nexperm(int[] p) { int n = p.length; for(int i=n-1;i>0;i--) { if(p[i-1]<p[i]) { int sw = n; for(int j=n-1;j>=i;j--) { if(p[i-1]<p[j]) { sw = j; break; } } int tmp = p[i-1]; p[i-1] = p[sw]; p[sw] = tmp; int[] r = new int[n]; for(int j=i;j<n;j++) { r[j] = p[n-1-j+i]; } for(int j=i;j<n;j++) { p[j] = r[j]; } return true; } } return false; } public int[] makeperm(int n) { int[] a = new int[n]; for(int i=0;i<n;i++) { a[i] = i; } return a; } public void timeout() throws InterruptedException { Thread.sleep(10000); } public int gray(int i) { for(int j=0;j<20;j++) { if(contains(i,j)) { graydiff = j; if(contains(i,j+1))graymark=-1; else graymark = 1; break; } } return i ^ (i>>1); } public void printjudge(boolean b, String y, String n) { System.out.println(b?y:n); } public void printYN(boolean b) { printjudge(b,"Yes","No"); } public void printyn(boolean b) { printjudge(b,"yes","no"); } public void reverse(int[] x) { int[] r = new int[x.length]; for(int i=0;i<x.length;i++)r[i] = x[x.length-1-i]; for(int i=0;i<x.length;i++)x[i] = r[i]; } public void reverse(long[] x) { long[] r = new long[x.length]; for(int i=0;i<x.length;i++)r[i] = x[x.length-1-i]; for(int i=0;i<x.length;i++)x[i] = r[i]; } public DoubleTriplet Line(double x1,double y1,double x2,double y2) { double a = y1-y2; double b = x2-x1; double c = x1*y2-x2*y1; return new DoubleTriplet(a,b,c); } public double putx(DoubleTriplet T,double x) { return -(T.a*x+T.c)/T.b; } public double puty(DoubleTriplet T,double y) { return -(T.b*y+T.c)/T.a; } public double Distance(DoublePair P,DoublePair Q) { return Math.sqrt((P.a-Q.a) * (P.a-Q.a) + (P.b-Q.b) * (P.b-Q.b)); } public double DistanceofPointandLine(DoublePair P,Triplet T) { return Math.abs(P.a*T.a+P.b*T.b+T.c) / Math.sqrt(T.a*T.a+T.b*T.b); } public boolean cross(long ax, long ay, long bx, long by, long cx, long cy, long dx, long dy) { if((ax-bx)*(cy-dy)==(ay-by)*(cx-dx)) { if(ax-bx!=0) { Range A = new Range(ax,bx); Range B = new Range(cx,dx); return A.kasanari(B)>0; }else { Range A = new Range(ay,by); Range B = new Range(cy,dy); return A.kasanari(B)>0; } } long ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax); long tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx); long tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx); long td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx); return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0)); } public boolean dcross(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) { double ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax); double tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx); double tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx); double td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx); return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0)); } void buildFac(){ fac = new long[10000003]; revfac = new long[10000003]; fac[0] = 1; for(int i=1;i<=10000002;i++){ fac[i] = (fac[i-1] * i)%mod; } revfac[10000002] = rev(fac[10000002])%mod; for(int i=10000001;i>=0;i--) { revfac[i] = (revfac[i+1] * (i+1))%mod; } isBuild = true; } void buildFacn(int n){ fac = new long[n+1]; revfac = new long[n+1]; fac[0] = 1; for(int i=1;i<=n;i++){ fac[i] = (fac[i-1] * i)%mod; } revfac[n] = rev(fac[n])%mod; for(int i=n-1;i>=0;i--) { revfac[i] = (revfac[i+1] * (i+1))%mod; } isBuild = true; } public long[] buildrui(int[] a) { int n = a.length; long[] ans = new long[n]; ans[0] = a[0]; for(int i=1;i<n;i++) { ans[i] = ans[i-1] + a[i]; } return ans; } public int[][] ibuildrui(int[][] a) { int n = a.length; int m = a[0].length; int[][] ans = new int[n][m]; for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { ans[i][j] = a[i][j]; } } for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { ans[i][j] += ans[i][j-1] + ans[i-1][j] - ans[i-1][j-1]; } } return ans; } public void buildruin(int[][] a) { int n = a.length; int m = a[0].length; for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { a[i][j] += a[i][j-1] + a[i-1][j] - a[i-1][j-1]; } } } public long[][] buildrui(int[][] a) { int n = a.length; int m = a[0].length; long[][] ans = new long[n][m]; for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { ans[i][j] = a[i][j]; } } for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { ans[i][j] += ans[i][j-1] + ans[i-1][j] - ans[i-1][j-1]; } } return ans; } public int getrui(int[][] r,int a,int b,int c,int d) { return r[c][d] - r[a-1][d] - r[c][b-1] + r[a-1][b-1]; } public long getrui(long[][] r,int a,int b,int c,int d) { if(a<0||b<0||c>=r.length||d>=r[0].length) return mod; return r[c][d] - r[a-1][d] - r[c][b-1] + r[a-1][b-1]; } long divroundup(long n,long d) { if(n==0)return 0; return (n-1)/d+1; } public long sigma(long i) { return i*(i+1)/2; } public int digit(long i) { int ans = 1; while(i>=10) { i /= 10; ans++; } return ans; } public int digitsum(long n) { int ans = 0; while(n>0) { ans += n%10; n /= 10; } return ans; } public int popcount(int i) { int ans = 0; while(i>0) { ans += i%2; i /= 2; } return ans; } public boolean contains(int S,int i) {return (S>>i&1)==1;} public int bitremove(int S,int i) {return S&(~(1<<i));} public int bitadd(int S,int i) {return S|(1<<i);} public boolean isSubSet(int S,int T) {return (S-T)==(S^T);} public boolean isDisjoint(int S,int T) {return (S+T)==(S^T);} public boolean contains(long S,int i) {return (S>>i&1)==1;} public long bitremove(long S,int i) {return S&(~(1<<i));} public long bitadd(long S,int i) {return S|(1<<i);} public boolean isSubSet(long S,long T) {return (S-T)==(S^T);} public boolean isDisjoint(long S,long T) {return (S+T)==(S^T);} public int isBigger(int[] d, int i) { int ok = d.length; int ng = -1; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d[mid]>i) { ok = mid; }else { ng = mid; } } return ok; } public int isSmaller(int[] d, int i) { int ok = -1; int ng = d.length; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d[mid]<i) { ok = mid; }else { ng = mid; } } return ok; } public int isBigger(long[] d, long i) { int ok = d.length; int ng = -1; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d[mid]>i) { ok = mid; }else { ng = mid; } } return ok; } public int isSmaller(long[] d, long i) { int ok = -1; int ng = d.length; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d[mid]<i) { ok = mid; }else { ng = mid; } } return ok; } public int isBigger(ArrayList<Integer> d, int i) { int ok = d.size(); int ng = -1; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d.get(mid)>i) { ok = mid; }else { ng = mid; } } return ok; } public int isSmaller(ArrayList<Integer> d, int i) { int ok = -1; int ng = d.size(); while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d.get(mid)<i) { ok = mid; }else { ng = mid; } } return ok; } public int isBigger(ArrayList<Long> d, long i) { int ok = d.size(); int ng = -1; while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d.get(mid)>i) { ok = mid; }else { ng = mid; } } return ok; } public int isSmaller(ArrayList<Long> d, long i) { int ok = -1; int ng = d.size(); while(Math.abs(ok-ng)>1) { int mid = (ok+ng)/2; if(d.get(mid)<i) { ok = mid; }else { ng = mid; } } return ok; } public HashSet<Integer> primetable(int m) { HashSet<Integer> pt = new HashSet<Integer>(); for(int i=2;i<=m;i++) { boolean b = true; for(int d:pt) { if(i%d==0) { b = false; break; } } if(b) { pt.add(i); } } return pt; } public ArrayList<Integer> primetablearray(int m) { ArrayList<Integer> al = new ArrayList<Integer>(); Queue<Integer> q = new ArrayDeque<Integer>(); for(int i=2;i<=m;i++) { q.add(i); } boolean[] b = new boolean[m+1]; while(!q.isEmpty()) { int e = q.poll(); if(!b[e]) { al.add(e); for(int j=1;e*j<=1000000;j++) { b[e*j] = true; } } } return al; } public boolean isprime(int e) { if(e==1) return false; for(int i=2;i*i<=e;i++) { if(e%i==0) return false; } return true; } public MultiSet Factrization(int e) { MultiSet ret = new MultiSet(); for(int i=2;i*i<=e;i++) { while(e%i==0) { ret.add(i); e /= i; } } if(e!=1)ret.add(e); return ret; } public int[] hipPush(int[] a){ int[] r = new int[a.length]; int[] s = new int[a.length]; for(int i=0;i<a.length;i++) { s[i] = a[i]; } Arrays.sort(s); HashMap<Integer,Integer> m = new HashMap<Integer,Integer>(); for(int i=0;i<a.length;i++) { m.put(s[i],i); } for(int i=0;i<a.length;i++) { r[i] = m.get(a[i]); } return r; } public HashMap<Integer,Integer> hipPush(ArrayList<Integer> l){ HashMap<Integer,Integer> r = new HashMap<Integer,Integer>(); TreeSet<Integer> s = new TreeSet<Integer>(); for(int e:l)s.add(e); int p = 0; for(int e:s) { r.put(e,p); p++; } return r; } public TreeMap<Integer,Integer> thipPush(ArrayList<Integer> l){ TreeMap<Integer,Integer> r = new TreeMap<Integer,Integer>(); Collections.sort(l); int b = -(1000000007+9393); int p = 0; for(int e:l) { if(b!=e) { r.put(e,p); p++; } b=e; } return r; } int[] count(int[] a) { int[] c = new int[max(a)+1]; for(int i=0;i<a.length;i++) { c[a[i]]++; } return c; } int[] count(int[] a, int m) { int[] c = new int[m+1]; for(int i=0;i<a.length;i++) { c[a[i]]++; } return c; } long max(long[] a){ long M = Long.MIN_VALUE; for(int i=0;i<a.length;i++){ if(M<=a[i]){ M =a[i]; maxdex = i; } } return M; } int max(int[] a){ int M = Integer.MIN_VALUE; for(int i=0;i<a.length;i++){ if(M<=a[i]){ M =a[i]; maxdex = i; } } return M; } long min(long[] a){ long m = Long.MAX_VALUE; for(int i=0;i<a.length;i++){ if(m>a[i]){ m =a[i]; mindex = i; } } return m; } int min(int[] a){ int m = Integer.MAX_VALUE; for(int i=0;i<a.length;i++){ if(m>a[i]){ m =a[i]; mindex = i; } } return m; } long sum(long[] a){ long s = 0; for(int i=0;i<a.length;i++)s += a[i]; return s; } long sum(int[] a){ long s = 0; for(int i=0;i<a.length;i++)s += a[i]; return s; } long sum(ArrayList<Integer> l) { long s = 0; for(int e:l)s += e; return s; } long gcd(long a, long b){ a = Math.abs(a); b = Math.abs(b); if(a==0)return b; if(b==0)return a; if(a%b==0) return b; else return gcd(b,a%b); } int igcd(int a, int b) { if(a%b==0) return b; else return igcd(b,a%b); } long lcm(long a, long b) {return a / gcd(a,b) * b;} public long perm(int a,int num) { if(!isBuild)buildFac(); return fac[a]*(rev(fac[a-num]))%mod; } void buildComb(int N) { comb = new long[N+1][N+1]; comb[0][0] = 1; for(int i=1;i<=N;i++) { comb[i][0] = 1; for(int j=1;j<N;j++) { comb[i][j] = comb[i-1][j-1]+comb[i-1][j]; if(comb[i][j]>mod)comb[i][j]-=mod; } comb[i][i] = 1; } } public long comb(int a,int num){ if(a-num<0)return 0; if(num<0)return 0; if(!isBuild)buildFac(); if(a>10000000) return combN(a,num); return fac[a] * ((revfac[num]*revfac[a-num])%mod)%mod; } long combN(int a,int num) { long ans = 1; for(int i=0;i<num;i++) { ans *= a-i; ans %= mod; } return ans * revfac[num] % mod; } long mulchoose(int n,int k) { if(k==0) return 1; return comb(n+k-1,k); } long rev(long l) {return pow(l,mod-2);} void buildpow(int l,int i) { pow = new long[i+1]; pow[0] = 1; for(int j=1;j<=i;j++) { pow[j] = pow[j-1]*l; if(pow[j]>mod)pow[j] %= mod; } } void buildrevpow(int l,int i) { revpow = new long[i+1]; revpow[0] = 1; for(int j=1;j<=i;j++) { revpow[j] = revpow[j-1]*l; if(revpow[j]>mod) revpow[j] %= mod; } } long pow(long l, long i) { if(i==0)return 1; else{ if(i%2==0){ long val = pow(l,i/2); return val * val % mod; } else return pow(l,i-1) * l % mod; } } long mon(int i) { long ans = 0; for(int k=2;k<=i;k++) { ans += (k%2==0?1:-1) * revfac[k]; ans += mod; } ans %= mod; ans *= fac[i]; return ans%mod; } long dictnum(int[] A) { int N = A.length; long ans = 0; BinaryIndexedTree bit = new BinaryIndexedTree(N+1); buildFacn(N); for(int i=1;i<=N;i++) { bit.add(i,1); } for(int i=1;i<=N;i++) { int a = A[i-1]; ans += bit.sum(a-1) * fac[N-i] % mod; bit.add(a,-1); } return (ans+1)%mod; } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
7c8b204ff12c097fe40898502d6b5d5b
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int[] c = new int[n]; for (int i = 0; i < n; i++) c[i] = sc.nextInt(); PriorityQueue<Integer> q = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return c[o2] - c[o1]; } }); int[] ans = new int[n]; for (int i = 0; i < k; i++) { q.add(i); } long delay = 0; for (int i = k; i < n; i++) { q.add(i); delay += 1l * (i - q.peek()) * c[q.peek()]; ans[q.remove()] = i; } int i = n; while(!q.isEmpty()) { delay += 1l * (i - q.peek()) * c[q.peek()]; ans[q.remove()] = i++; } out.println(delay); for (int j = 0; j < n; j++) { out.print(ans[j] + 1 + " "); } out.println(); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException{ br = new BufferedReader(new FileReader(file));} public String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } 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); } } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
8ef507993bb9133936b031779e27de0d
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class A extends PrintWriter { void run() { int n = nextInt(), k = nextInt(); long[] c = new long[n]; for (int i = 0; i < n; i++) { c[i] = nextInt(); } PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { return Long.compare(c[j], c[i]); } }); int[] t = new int[n]; int p = 0; for (int i = 0; i < k; i++) { queue.add(p++); } for (int i = 0; i < n; i++) { if (p < n) { queue.add(p++); } int j = queue.poll(); t[j] = i + k + 1; } long sum = 0; for (int i = 0; i < n; i++) { sum += c[i] * (t[i] - i - 1); } println(sum); for (int i = 0; i < n; i++) { print(t[i]); print(' '); } } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public A(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; A solution = new A(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(A.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
b5dd1eab1cfb4f2a9f4d5367d0b5359d
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.io.*; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static MyScanner in; static PrintWriter out; public static void main(String[] args) throws IOException { in = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), false); int n = in.nextInt(), k = in.nextInt(); int[] arr = in.nextInts(n); PriorityQueue<Pair> q = buildQueue(arr); TreeSet<Integer> set = buildSet(n, k); int[] ans = new int[n]; while (!q.isEmpty()) { Pair p = q.poll(); // System.out.println(p); int a = set.ceiling(p.b); ans[p.b - 1] = a; set.remove(a); } long cnt = 0; int index = 0; for (int a : ans) { index++; cnt += (long) (a - index) * arr[index - 1]; } out.println(cnt); for (int a : ans) out.print(a + " "); out.flush(); } static PriorityQueue<Pair> buildQueue(int[] arr) { PriorityQueue<Pair> q = new PriorityQueue<>(); for (int i = 0; i < arr.length; i++) { q.add(new Pair(arr[i], i + 1)); } return q; } static TreeSet<Integer> buildSet(int n, int k) { LinkedList<Integer> list = new LinkedList<>(); for (int i = k + 1; i <= n + k; i++) { list.add(i); } return new TreeSet<>(list); } } class Pair implements Comparable { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Object o) { Pair other = (Pair) o; return Integer.compare(other.a, a); } @Override public String toString() { return "Pair{" + "a=" + a + ", b=" + b + '}'; } } class MyScanner implements Closeable { public static final String CP1251 = "cp1251"; private final BufferedReader br; private StringTokenizer st; private String last; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String path) throws IOException { br = new BufferedReader(new FileReader(path)); } public MyScanner(String path, String decoder) throws IOException { br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder)); } public void close() throws IOException { br.close(); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(); } public String next(String delim) throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(delim); } public String nextLine() throws IOException { st = null; return (last == null) ? br.readLine() : last; } public boolean hasNext() { if (st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) { last = br.readLine(); st = new StringTokenizer(last); } } catch (Exception e) { return false; } return true; } public String[] nextStrings(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = next(); return arr; } public String[] nextLines(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = nextLine(); return arr; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextInts(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public Integer[] nextIntegers(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[][] next2Ints(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } public long nextLong() throws IOException { return Long.parseLong(next()); } public long[] nextLongs(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public long[][] next2Longs(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } public double nextDouble() throws IOException { return Double.parseDouble(next().replace(',', '.')); } public double[] nextDoubles(int size) throws IOException { double[] arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } public double[][] next2Doubles(int n, int m) throws IOException { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextDouble(); return arr; } public boolean nextBool() throws IOException { String s = next(); if (s.equalsIgnoreCase("true") || s.equals("1")) return true; if (s.equalsIgnoreCase("false") || s.equals("0")) return false; throw new IOException("Boolean expected, String found!"); } }
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
2ef6403e5572939f1c2e433dbb754af6
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.util.*; import java.io.*; import java.util.*; public class test { /* private static class IntegerPair implements Comparable { public Integer first; public Integer second; public IntegerPair(Integer f, Integer s) { first = f; second = s; } public int compareTo(Object obj) { if (!this.first.equals( ((IntegerPair)obj).first) ) { return first - ((IntegerPair)obj).first; } else { return second - ((IntegerPair)obj).second; } } } */ /* //Arrays.sort(data, new MyComparator()); //if a<b return -1 //if a>b return 1 //if a==b return 0 private static class MyComparator implements Comparator<Long> { @Override public int compare(Long a, Long b) { int a3 = 0; int b3 = 0; while(a%3==0) { a/=3; a3++; } while(b%3==0) { b/=3; b3++; } if(a3>b3) { return -1; } else if(a3 == b3 && a<b) { return -1; } return 1; } } */ private static class IntegerPair implements Comparable { public Integer first; public Integer second; public IntegerPair(Integer f, Integer s) { first = f; second = s; } public int compareTo(Object obj) { return first - ((IntegerPair)obj).first; } } // public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int[] QQQ = new int[n+1]; PriorityQueue<IntegerPair> pQueue = new PriorityQueue<IntegerPair>(); for(int i=1;i<=k;i++) { IntegerPair x = new IntegerPair( -sc.nextInt(), i); pQueue.add( x ); } long answer = 0; for(int i= k+1;i<=n + k;i++) { if(i<=n) { IntegerPair x = new IntegerPair( -sc.nextInt(), i); pQueue.add( x ); } IntegerPair head = pQueue.poll(); answer -= ((long)head.first) * (i - head.second); QQQ[head.second] = i; } out.println(answer); for(int i=1;i<=n;i++) { out.print(QQQ[i] + " "); } out.flush(); out.close(); } private static class Scanner { BufferedReader bf; StringTokenizer st; public Scanner() { bf = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } } /* done 7 9 8 10 15 */
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
187c6ddabd378211b14f1662795deec5
train_002.jsonl
1504702500
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
512 megabytes
import java.util.*; import java.io.*; import java.util.*; public class test { /* private static class IntegerPair implements Comparable { public Integer first; public Integer second; public IntegerPair(Integer f, Integer s) { first = f; second = s; } public int compareTo(Object obj) { if (!this.first.equals( ((IntegerPair)obj).first) ) { return first - ((IntegerPair)obj).first; } else { return second - ((IntegerPair)obj).second; } } } */ /* //Arrays.sort(data, new MyComparator()); //if a<b return -1 //if a>b return 1 //if a==b return 0 private static class MyComparator implements Comparator<Long> { @Override public int compare(Long a, Long b) { int a3 = 0; int b3 = 0; while(a%3==0) { a/=3; a3++; } while(b%3==0) { b/=3; b3++; } if(a3>b3) { return -1; } else if(a3 == b3 && a<b) { return -1; } return 1; } } */ private static class IntegerPair implements Comparable<IntegerPair> { public Integer first; public Integer second; public IntegerPair(Integer f, Integer s) { first = f; second = s; } public int compareTo(IntegerPair obj) { return first - obj.first; } } // public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int[] QQQ = new int[n+1]; PriorityQueue<IntegerPair> pQueue = new PriorityQueue<IntegerPair>(); for(int i=1;i<=k;i++) { IntegerPair x = new IntegerPair( -sc.nextInt(), i); pQueue.add( x ); } long answer = 0; for(int i= k+1;i<=n + k;i++) { if(i<=n) { IntegerPair x = new IntegerPair( -sc.nextInt(), i); pQueue.add( x ); } IntegerPair head = pQueue.poll(); answer -= ((long)head.first) * (i - head.second); QQQ[head.second] = i; } out.println(answer); for(int i=1;i<=n;i++) { out.print(QQQ[i] + " "); } out.flush(); out.close(); } private static class Scanner { BufferedReader bf; StringTokenizer st; public Scanner() { bf = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } } } /* done 7 9 8 10 15 */
Java
["5 2\n4 2 1 10 2"]
1 second
["20\n3 6 7 4 5"]
NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Java 8
standard input
[ "greedy" ]
8c23fcc84c6921bc2a95ff0586516321
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
1,500
The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
standard output
PASSED
944956f2314dad5393a0e473aa82c4b4
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.util.Scanner; public class F { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int xl = s.nextInt(); int xr = xl; int[] start = new int[n]; int[] end = new int[n]; for (int i = 0; i < n; i++) { start[i] = s.nextInt(); end[i] = s.nextInt(); } long cost = 0; for (int i = 0; i < n; i++) { if (end[i] < xl) { cost += xl - end[i]; xr = xl; xl = end[i]; } else if (start[i] > xr) { cost += start[i] - xr; xl = xr; xr = start[i]; } else { xl = Math.max(xl, start[i]); xr = Math.min(xr, end[i]); } } System.out.println(cost); } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
a9d863a403effa88e8b29d3a8e01079a
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map; public class bulbo{ public static void main(String args[]){ FasterScanner s=new FasterScanner(); int n=s.nextInt(); long x=s.nextInt(); long l=x; long r=x; long mn; long mx; long ans=0; for(int i=0;i<n;i++){ long f=s.nextInt(); long t=s.nextInt(); mn=Math.max(l,f); mx=Math.min(r,t); if(mn<=mx){ l=mn; r=mx; } else{ if(l>t){ ans+=l-t; r=l; l=t; } else{ ans+=f-r; l=r; r=f; } } } System.out.println(ans); } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
8c3f85b89bf69c3518b051a408ec0e55
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class F_BubbleCup_Final { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int x = in.nextInt(); Point[] data = new Point[n + 1]; data[0] = new Point(x, x); TreeSet<Integer> set = new TreeSet(); set.add(x); for (int i = 1; i <= n; i++) { data[i] = new Point(in.nextInt(), in.nextInt()); set.add(data[i].x); set.add(data[i].y); } HashMap<Integer, Integer> map = new HashMap(); int index = 0; ArrayList<Integer> pos = new ArrayList(set); for (int i : set) { map.put(i, index++); } long[][] root = new long[2][index]; int start = map.get(data[n - 1].x); int end = map.get(data[n - 1].y); long[][] fast = new long[2][index]; for (int i = index - 1; i >= 0; i--) { int v = pos.get(i); // System.out.println(map.containsKey(v) + " " + v); if (data[n].x <= v && v <= data[n].y) { root[0][i] = 0; } else { root[0][i] = min(abs(v - data[n].x), abs(v - data[n].y)); } if (i <= start) { fast[0][i] = root[0][i]; if (i + 1 <= start) { fast[0][i] = min(fast[0][i], fast[0][i + 1]); } } } for (int i = end; i < index; i++) { fast[0][i] = root[0][i]; if (i - 1 >= end) { fast[0][i] = min(fast[0][i], fast[0][i - 1]); } } // System.out.println(pos); // System.out.println(Arrays.toString(fast[0])); int cur = 1; for (int i = n - 1; i >= 0; i--) { start = i - 1 >= 0 ? map.get(data[i - 1].x) : -1; end = i - 1 >= 0 ? map.get(data[i - 1].y) : index; for (int j = index - 1; j >= 0; j--) { int v = pos.get(j); long tmp; if (data[i].x <= v && v <= data[i].y) { root[cur][j] = root[1 - cur][j]; } else { long a = abs(data[i].x - v); long b = abs(data[i].y - v); if (a < b) { tmp = a + fast[1 - cur][j]; } else { tmp = b + fast[1 - cur][j]; } root[cur][j] = tmp; } if (j <= start) { fast[cur][j] = root[cur][j]; if (j + 1 <= start) { fast[cur][j] = min(fast[cur][j], fast[cur][j + 1]); } } } for (int j = end; j < index; j++) { fast[cur][j] = root[cur][j]; if (j - 1 >= end) { fast[cur][j] = min(fast[cur][j], fast[cur][j - 1]); } } //System.out.println(Arrays.toString(fast[cur]) + " " + Arrays.toString(root[cur])); cur = 1 - cur; } out.println(root[1 - cur][map.get(x)]); out.close(); } static long min(long a, long b) { return a < b ? a : b; } static long abs(long v) { return v < 0 ? -v : v; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
2f23aca5b4a57e17c58183db57f72cb1
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.lang.*; import java.math.*; import static java.lang.Math.*; public class Solution implements Runnable { void solve() throws Exception { int n = sc.nextInt() + 1; int[] l = new int[n]; int[] r = new int[n]; l[0] = r[0] = sc.nextInt(); TreeSet<Integer> x = new TreeSet<Integer>(); x.add(l[0]); for (int i = 1; i < n; i++) { l[i] = sc.nextInt(); r[i] = sc.nextInt(); x.add(l[i]); x.add(r[i]); } int m = x.size(); int[] px = new int[m]; m = 0; while (!x.isEmpty()) { px[m++] = x.pollFirst(); } long[] dp = new long[m]; for (int i = 0; i < m; i++) { dp[i] = abs(l[0] - px[i]); } long[] lf = new long[m]; long[] rg = new long[m]; for (int i = 1; i < n; i++) { for (int j = 0; j < m; j++) { if (px[j] < l[i]) { dp[j] += l[i] - px[j]; } if (px[j] > r[i]) { dp[j] += px[j] - r[i]; } lf[j] = (j > 0 ? lf[j - 1] : Long.MAX_VALUE); lf[j] = min(lf[j], dp[j] - px[j]); } for (int j = m - 1; j >= 0; --j) { rg[j] = (j < m - 1 ? rg[j + 1] : Long.MAX_VALUE); rg[j] = min(rg[j], dp[j] + px[j]); } for (int j = 0; j < m; j++) { dp[j] = min(dp[j], px[j] + lf[j]); dp[j] = min(dp[j], rg[j] - px[j]); } } long ans = Long.MAX_VALUE; for (int i = 0; i < m; i++) { ans = min(ans, dp[i]); } out.println(ans); } BufferedReader in; PrintWriter out; FastScanner sc; final String INPUT_FILE = "stdin"; final String OUTPUT_FILE = "stdout"; static Throwable throwable; public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); thread.run(); if (throwable != null) throw throwable; } public void run() { try { if (INPUT_FILE.equals("stdin")) in = new BufferedReader(new InputStreamReader(System.in)); else in = new BufferedReader(new FileReader(INPUT_FILE)); if (OUTPUT_FILE.equals("stdout")) out = new PrintWriter(System.out); else out = new PrintWriter(new FileWriter(OUTPUT_FILE)); sc = new FastScanner(in); solve(); } catch (Exception e) { throwable = e; } finally { out.close(); } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws Exception { while (strTok == null || !strTok.hasMoreTokens()) strTok = new StringTokenizer(reader.readLine()); return strTok.nextToken(); } public boolean EOF() throws Exception { if (strTok != null && strTok.hasMoreTokens()) { return false; } else { String line = reader.readLine(); if (line == null) return true; strTok = new StringTokenizer(line); return false; } } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
0a5c82404a77b7afa73924e74936e510
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class F implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new F(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; protected int precision; protected String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; static final boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// static final boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// static final long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } static final Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// final static long INF = 1000L * 1000 * 1000 * 1000 * 1000; void solve() throws IOException { int segmentsCount = readInt(); int startPosition = readInt(); Point[] segments = readPointArray(segmentsCount); Set<Integer> positionsSet = new HashSet<Integer>(); positionsSet.add(startPosition); for (Point segment : segments) { positionsSet.add(segment.x); positionsSet.add(segment.y); } Point prevSegment = new Point(startPosition, startPosition); for (Point segment : segments) { if (prevSegment.x > segment.y) { int delta = prevSegment.x - segment.y; positionsSet.add(segment.y + delta); // positionsSet.add(prevSegment.x - delta); } if (prevSegment.y < segment.x) { int delta = segment.x - prevSegment.y; positionsSet.add(prevSegment.y + delta); // positionsSet.add(segment.x - delta); } prevSegment = segment; } int[] positions = new int[positionsSet.size()]; { int curIndex = 0; for (int i : positionsSet) { positions[curIndex++] = i; } } Arrays.sort(positions); int n = positions.length; Map<Integer, Integer> indexes = new HashMap<Integer, Integer>(); for (int index = 0; index < n; ++index) { indexes.put(positions[index], index); } long[] curDp = new long[n]; Arrays.fill(curDp, INF); long[] nextDp = new long[n]; Arrays.fill(nextDp, INF); long[] prefMins = new long[n]; long[] suffMins = new long[n]; curDp[indexes.get(startPosition)] = 0; for (int time = 0; time < segmentsCount; ++time) { prefMins[0] = curDp[0] - positions[0]; for (int i = 1; i < n; ++i) { prefMins[i] = min(prefMins[i - 1], curDp[i] - positions[i]); } suffMins[n - 1] = curDp[n - 1] + positions[n - 1]; for (int i = n - 2; i >= 0; --i) { suffMins[i] = min(suffMins[i + 1], curDp[i] + positions[i]); } Point segment = segments[time]; int leftPosition = segment.x; int rightPosition = segment.y; for (int index = 0; index < n; ++index) { int position = positions[index]; long minMovingCost = min(prefMins[index] + position, suffMins[index] - position); long minLightCost = 0; if (position < leftPosition) { minLightCost = leftPosition - position; } else if (position > rightPosition) { minLightCost = position - rightPosition; } nextDp[index] = minMovingCost + minLightCost; } for (int index = 0; index < n; ++index) { curDp[index] = nextDp[index]; nextDp[index] = INF; } } long ans = INF; for (int index = 0; index < n; ++index) { ans = min(ans, curDp[index]); } out.println(ans); } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
2a67edb8a4c9355c847befa10efe17d3
train_002.jsonl
1441526400
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class F implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new F(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; protected int precision; protected String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; static final boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// static final boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// static final long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } static final Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// final static long INF = 1000L * 1000 * 1000 * 1000 * 1000; void solve() throws IOException { int segmentsCount = readInt(); int startPosition = readInt(); Point[] segments = readPointArray(segmentsCount); Set<Integer> positionsSet = new HashSet<Integer>(); positionsSet.add(startPosition); for (Point segment : segments) { positionsSet.add(segment.x); positionsSet.add(segment.y); } // Point prevSegment = new Point(startPosition, startPosition); // for (Point segment : segments) { // if (prevSegment.x > segment.y) { // int delta = prevSegment.x - segment.y; // positionsSet.add(segment.y + delta); //// positionsSet.add(prevSegment.x - delta); // } // // if (prevSegment.y < segment.x) { // int delta = segment.x - prevSegment.y; // positionsSet.add(prevSegment.y + delta); //// positionsSet.add(segment.x - delta); // } // // prevSegment = segment; // } // int[] positions = new int[positionsSet.size()]; { int curIndex = 0; for (int i : positionsSet) { positions[curIndex++] = i; } } Arrays.sort(positions); int n = positions.length; Map<Integer, Integer> indexes = new HashMap<Integer, Integer>(); for (int index = 0; index < n; ++index) { indexes.put(positions[index], index); } long[] curDp = new long[n]; Arrays.fill(curDp, INF); long[] nextDp = new long[n]; Arrays.fill(nextDp, INF); long[] prefMins = new long[n]; long[] suffMins = new long[n]; curDp[indexes.get(startPosition)] = 0; for (int time = 0; time < segmentsCount; ++time) { prefMins[0] = curDp[0] - positions[0]; for (int i = 1; i < n; ++i) { prefMins[i] = min(prefMins[i - 1], curDp[i] - positions[i]); } suffMins[n - 1] = curDp[n - 1] + positions[n - 1]; for (int i = n - 2; i >= 0; --i) { suffMins[i] = min(suffMins[i + 1], curDp[i] + positions[i]); } Point segment = segments[time]; int leftPosition = segment.x; int rightPosition = segment.y; for (int index = 0; index < n; ++index) { int position = positions[index]; long minMovingCost = min(prefMins[index] + position, suffMins[index] - position); long minLightCost = 0; if (position < leftPosition) { minLightCost = leftPosition - position; } else if (position > rightPosition) { minLightCost = position - rightPosition; } nextDp[index] = minMovingCost + minLightCost; } for (int index = 0; index < n; ++index) { curDp[index] = nextDp[index]; nextDp[index] = INF; } } long ans = INF; for (int index = 0; index < n; ++index) { ans = min(ans, curDp[index]); } out.println(ans); } }
Java
["5 4\n2 7\n9 16\n8 10\n9 17\n1 6"]
1 second
["8"]
NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Java 7
standard input
[ "dp", "greedy" ]
2452c30e7820ae2fa9a9ff4698760326
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≤ n ≤ 5000 1 ≤ x ≤ 109 1 ≤ lstart ≤ lend ≤ 109
2,100
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
standard output
PASSED
46319d40e1b1eb3ba6ad2c1b2c2e2090
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); int[][] board = new int[n][n]; //automatically initialized with '0' int row = 0; int col = n/2; int num = 1; while ( num <= n*n ) { board[row][col] = num; num++; int tempCol = (col + 1)%n; int tempRow = (row - 1) >= 0 ? row-1 : n-1; if( board[tempRow][tempCol] != 0 ) { row = (row+1)%n; } else { row = tempRow; col = tempCol; } } for( int i = 0 ; i < n ; i++) { for( int j = 0 ; j < n ; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
9fe5ec2dd871e7b2f73e3eeeb9893062
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; import java.io.BufferedWriter; import java.io.OutputStreamWriter; public class Q2 { static ArrayList<Integer>[] arr; static FasterScanner sc; static boolean[] b; static Stack<Integer> s = new Stack<Integer>(); //static StringBuilder str; public static void main(String[] args) throws IOException { sc = new FasterScanner(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt(); int arr[][] = new int[n][n]; Stack<Integer> odd= new Stack<>(); Stack<Integer> even= new Stack<>(); for(int i = 1;i<=n*n;i++){ if(i%2 == 1) odd.push(i); else even.push(i); } for(int i =0;i<=n/2;i++){ boolean x = true; int j = n/2; int k = 2*i+1; int y = 0; while(k>0){ if(x){ arr[i][j-y] = odd.pop(); y+=1; x = false; } else { x =true; arr[i][j+y] = odd.pop(); } k--; } } for(int i =0;i<n/2;i++){ boolean x = true; int j = n/2; int k = 2*i+1; int y = 0; while(k>0){ if(x){ arr[n-i-1][j-y] = odd.pop(); y+=1; x = false; } else { x =true; arr[n-1-i][j+y] = odd.pop(); } k--; } } for(int i =0 ;i<n;i++){ for(int j = 0;j<n;j++){ if(arr[i][j] == 0) arr[i][j] = even.pop(); System.out.print(arr[i][j]+" "); } System.out.println(); } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
dff6e9caf6aa32e0fac60a5c564d776e
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
//package acm.cf1; import java.util.*; public class Main { static int odd,even; static int nextodd(){ odd+=2; return odd; } static int nexteven(){ even+=2; return even; } static void output(int a[][],int n){ // System.out.println("???"); for (int i = 1;i <= n;++i){ for (int j = 1;j <= n;++j){ // System.out.println(i+","+j); System.out.print(a[i][j] + ((j==n)?"\n":" ")); } } } static void Solve(int n){ // System.out.println("<>"); int a[][] = new int[n+4][n+4]; int mid = n/2+1; odd = -1;even = 0; int times = 0; for (int i = 1;i <= n;++i){ // System.out.println(i); a[i][mid] = nextodd(); for (int j = mid -1,k = mid + 1,t = 1;j > 0;--j,++k,++t){ if (t > times){ a[i][j] = nexteven(); a[i][k] = nexteven(); }else { a[i][j] = nextodd(); a[i][k] = nextodd(); } } if (i < mid) times++; else times--; } // System.out.println("???"); output(a,n); } public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner in = new Scanner (System.in); while (in.hasNext()){ Solve(in.nextInt()); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
9f3366544540fe3838b92edf8e1684a5
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; /** * * @author alanl */ public class Main{ static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] args) throws IOException{ int n = readInt(), arr[][] = new int[n][n], cnt = 1, start = n/2; for(int i = 0; i<n; i++){ for(int j = start; j<start+cnt; j++){ arr[i][j] = 1; } if(i<n/2){ start--; cnt+=2; } else{ start++; cnt-=2; } } int even = 2, odd = 1; for(int i = 0; i<n; i++){ for(int j = 0; j<n; j++){ if(arr[i][j]%2==0){ arr[i][j] = even; even+=2; } else{ arr[i][j] = odd; odd+=2; } System.out.print(arr[i][j]+" "); } System.out.println(); } } static String next () throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine().trim()); return st.nextToken(); } static long readLong () throws IOException { return Long.parseLong(next()); } static int readInt () throws IOException { return Integer.parseInt(next()); } static double readDouble () throws IOException { return Double.parseDouble(next()); } static char readChar () throws IOException { return next().charAt(0); } static String readLine () throws IOException { return input.readLine().trim(); } /* stuff you should look for * int overflow, array bounds * special cases (n=1?) * do smth instead of nothing and stay organized * WRITE STUFF DOWN * DON'T GET STUCK ON ONE APPROACH // Did you read the bounds? // Did you make typos? // Are there edge cases (N=1?) // Are array sizes proper (scaled by proper constant, for example 2* for koosaga tree) // Integer overflow? // DS reset properly between test cases? // Is using long longs causing TLE? // Are you using floating points? */ }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
f0b94cc81f289c373649a5fceb013ea8
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; public class problem710C { public static void main(String[] args) { Scanner console = new Scanner(System.in); int size = console.nextInt(); if (size == 1) { System.out.println("1"); return; } PriorityQueue<Integer> odd = new PriorityQueue<>(); PriorityQueue<Integer> even = new PriorityQueue<>(); for (int i = 1; i<=size*size; i++) { if (i%2 == 0) even.add(i); else odd.add(i); } for (int i = 0; i<size/2; i++) { for (int j = 0; j<size/2-i; j++) { System.out.print(even.remove()+" "); } for (int j = 0; j<1+2*i; j++) { System.out.print(odd.remove()+" "); } for (int j = 0; j<size/2-i; j++) { System.out.print(even.remove()+" "); } System.out.println(); } for (int i = 0; i<size; i++) System.out.print(odd.remove()+" "); System.out.println(); for (int i = 0; i<size/2; i++) { for (int j = 0; j<i+1; j++) { System.out.print(even.remove()+" "); } for (int j = 0; j<size-2-2*i; j++) { System.out.print(odd.remove()+" "); } for (int j = 0; j<i+1; j++) { System.out.print(even.remove()+" "); } System.out.println(); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
4ebc58661dbaca6e3b5eaeaa45f93c2a
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception{ BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(inp.readLine()); int r = n >>> 1; assert (n % 2 == 1); int o = 1, e = 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.abs(i - r) - 1 < j && j < n - Math.abs(i - r)) { // || j > n - r + Math.abs(i - r)) System.out.print(o + " "); o += 2; } else { System.out.print(e + " "); e += 2; } } System.out.println(); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
b506df4c2c36d37f186528058592f4ba
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class C{ public static void main( String[] args ){ Scanner scanner = new Scanner( System.in ); int n = scanner.nextInt( ); int[][] m = new int[n][n]; for( int i = 0; i < n; ++i ){ for( int j = 0; j < n; ++j ){ m[i][j] = n * i + j + 1; } } for( int i = ( ( n + 1 >> 1 ) & 1 ); i < ( n >> 1 ); i += 2 ){ int last = m[i + 1][i]; for( int j = 0; j < ( n - 2 * i - 1 ) * 4; ++j ){ int cur; if( j < n - 2 * i ){ cur = m[i][i + j]; m[i][i + j] = last; }else if( j < ( n - 2 * i ) * 2 - 1 ){ j -= n - 2 * i; cur = m[i + j + 1][n - i - 1]; m[i + j + 1][n - i - 1] = last; j += n - 2 * i; }else if( j < ( n - 2 * i ) * 3 - 2 ){ j -= ( n - 2 * i ) * 2 - 1; cur = m[n - i - 1][n - i - j - 2]; m[n - i - 1][n - i - j - 2] = last; j += ( n - 2 * i ) * 2 - 1; }else{ j -= ( n - 2 * i ) * 3 - 2; cur = m[n - i - j - 2][i]; m[n - i - j - 2][i] = last; j += ( n - 2 * i ) * 3 - 2; } last = cur; } } for( int i = 0; i < n; ++i ){ for( int j = 0; j < n; ++j ){ System.out.print( m[i][j] + " " ); } System.out.println( ); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
e9038c9b7a96d8711b1126848d148642
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int n = ri(); int[][] A = new int[n][n]; int val = 1; int l = 1; for (int i = n / 2; i >= 0; i--) { val = fill(A, i, i, l, val); l += 2; } for (int[] row : A) { for (int aij : row) pw.print(aij + " "); pw.println(); } } int fill(int[][] A, int r, int c, int n, int X) { if (n == 1) { A[r][c] = X++; return X; } int init = X; if ((n/2+1) % 2 == 1) { X++; } for (int i = c; i < c + n - 1; i++) A[r][i] = X++; for (int i = r; i < r + n - 1; i++) A[i][c+n-1] = X++; for (int i = c+n-1; i > c; i--) A[r+n-1][i] = X++; for (int i = r+n-1; i > r; i--) A[i][c] = X++; if ((n/2+1) % 2 == 1) { A[r+1][c] = init; X--; } return X; } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
b7889c1a1bf2b6a45dd926f621265b36
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
/** * Created by ankeet on 8/22/16. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C710 { static FastReader in = null; static PrintWriter out = null; public static void solve() { int n = in.nint(); int[][] mat = new int[n][n]; int ct = 1; boolean up =true; for(int i=0; i<n; i++) { int spos = (n-ct)/2; int fpos = n-1-spos; for(int j=spos; j<=fpos; j++) { mat[i][j] = 1; } if(ct == n) { up = false; } if(up) ct+=2; else ct-=2; } int odd = 1; int even = 2; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(mat[i][j] == 1) { mat[i][j] = odd; odd+=2; } else { mat[i][j] = even; even+=2; } out.print(mat[i][j]); if(j!=n-1) out.print(" "); } out.println(); } } public static void main(String[] args) { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } static class FastReader { BufferedReader read; StringTokenizer tokenizer; public FastReader(InputStream in) { read = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(read.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nint() { return Integer.parseInt(next()); } public long nlong() { return Long.parseLong(next()); } public double ndouble() { return Double.parseDouble(next()); } public int[] narr(int n) { int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = nint(); } return a; } public long[] nlarr(int n) { long[] a = new long[n]; for(int i=0; i<n; ++i) { a[i] = nlong(); } return a; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
94de295e648b5b4cd126ca518c9a327d
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class CF710C { public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream(new File("input")); OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int last_odd = 1; int last_even = 2; int mid = (n + 1) / 2; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (Math.abs(i - mid) + Math.abs(j - mid) <= n/2) { out.print(last_odd + " "); last_odd += 2; } else { out.print(last_even + " "); last_even += 2; } } out.println(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
6c115d753c0db796ca5926e6f6e5aa5e
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static void generateSquare(int n) { int[][] magicSquare = new int[n][n]; // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) //3rd condition { j = n - 2; i = 0; } else { //1st condition helper if next number // goes to out of square's right side if (j == n) { j = 0; } //1st condition helper if next number is // goes to out of square's upper side if (i < 0) { i = n - 1; } } //2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else //set number { magicSquare[i][j] = num++; } //1st condition j++; i--; } // print magic square for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { System.out.print(magicSquare[i][j] + " "); } System.out.println(); } } // driver program public static void main(String[] args) { // Works only when n is odd Scanner scanner = new Scanner(System.in); int n = 0; n = scanner.nextInt(); generateSquare(n); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
b2934c4e84770f97ea6ec59e09d8cb8b
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.*; import java.util.*; public class Sweata { // Function to generate odd sized magic squares static void generateSquare(int n) { int[][] magicSquare = new int[n][n]; // Initialize position for 1 int i = n/2; int j = n-1; // One by one put all values in magic square for (int num=1; num <= n*n; ) { if (i==-1 && j==n) //3rd condition { j = n-2; i = 0; } else { //1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; //1st condition helper if next number is // goes to out of square's upper side if (i < 0) i=n-1; } //2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else //set number magicSquare[i][j] = num++; //1st condition j++; i--; } for(i=0; i<n; i++) { for(j=0; j<n; j++) System.out.print(magicSquare[i][j]+" "); System.out.println(); } } // driver program public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); generateSquare(n); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
9809c1441c2efe20740b9131dcc2c087
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Task710C { public static void main(String[] args) throws IOException { InputScanner is = new InputScanner(); int n = is.nextInt(); int ans[][] = new int[n][n]; int num = 1; int start = n / 2; int end = 1; for (int i = 0; i < n; i++) { for (int j = start; j < start + end; j++){ ans[i][j] = num; num += 2; } if (i < n / 2) { start--; end += 2; } else { start++; end -= 2; } } num = 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (ans[i][j] == 0) { ans[i][j] = num; num += 2; } } } StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sb.append(ans[i][j] + " "); } if (i!=n-1) sb.append("\n"); } System.out.println(sb); } static class InputScanner { BufferedReader br; StringTokenizer st; public InputScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws IOException { String next = next(); return Integer.parseInt(next); } public long nextLong() throws IOException { String next = next(); return Long.parseLong(next); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
175ef9584f0eb30fd108f9490594c250
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
/* * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * * And Logic is the strongest weapon. * */ import java.io.*; import java.math.*; import java.util.*; import java.util.Map.Entry; public class Coding { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static int infi = (int) 1e9; //private static final int N = 1234567; //private static final double MOD = 1e9 + 7; //Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); static int n0 = 2, n1 = 1; public static int p0() { n0 += 2; return n0 - 2; } public static int p1() { n1 += 2; return n1 - 2; } public static int soln() { int n = nI(); int man[][] = new int[n][n]; int now = 1; for (int i = 0; i < n; ++i) { int x = now / 2; int st = n / 2; for (int j = st - x; j <= st + x; ++j) { man[i][j] = 1; } if (i * 2 + 1 < n) { now += 2; } else { now -= 2; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (man[i][j] != 0) { pw.print(p1()+" "); } else { pw.print(p0()+" "); } } pw.println(); } return 0; } public static void main(String[] args) throws FileNotFoundException { InputReader(System.in); //pw = new PrintWriter(new FileOutputStream("ans.txt")); pw = new PrintWriter(System.out); soln(); pw.close(); } /* ********************************************************************************************* */ public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private double nD() { return Double.parseDouble(nS()); } private static int nI() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nL() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nS() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nLi() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
d761a99a8614cf56e8c234d72283e6f2
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class MagicOddSquare { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int counter=0; int n = input.nextInt(); int val =1; int x1 = n/2; int x2 = n/2; int y = 0; int value= 1; int[][] arr = new int[n][n]; for( y=0; y<=n/2;y++){ for(int i=x1; i<=x2;i++){ arr[i][y] = value; value+=2; } x1--; x2++; } x1+=2; x2-=2; //System.out.println(x1+" "+x2); for( y=n/2+1; y<n;y++){ for(int i=x1; i<=x2;i++){ arr[i][y] = value; value+=2; } x1++; x2--; } val=2; for(int i=0; i<n;i++){ for(int j=0; j<n;j++){ if(arr[i][j]==0){arr[i][j] = val;val+=2;} } } for(int i=0; i<n;i++){ for(int j=0;j<n;j++)System.out.print(arr[i][j]+" "); System.out.println(); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
698fbbda1fffba63792e71e11589e1e1
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args)throws IOException { PrintStream out= new PrintStream(System.out); Reader sc=new Reader(); int n=sc.i(); int odd[]=new int[(n*n)/2+1]; int even[]=new int[(n*n)/2]; int counter=0; for(int i=1;i<=n*n;i+=2) odd[counter++]=i; counter=0; for(int i=2;i<=n*n;i+=2) even[counter++]=i; int ans[][]=new int[n][n]; int counter1=0;int counter2=0; int marker=0; for(int i=0;i<n/2;i++) { for(int j=0;j<n/2-marker;j++) out.print(even[counter2++]+" "); for(int j=n/2-marker;j<=n/2+marker;j++) out.print(odd[counter1++]+" "); for(int j=n/2+marker+1;j<n;j++) out.print(even[counter2++]+" "); out.println(); marker++; } marker--; for(int i=0;i<n;i++) out.print(odd[counter1++]+" "); out.println(); for(int i=n/2+1;i<n;i++) { for(int j=0;j<n/2-marker;j++) out.print(even[counter2++]+" "); for(int j=n/2-marker;j<=n/2+marker;j++) out.print(odd[counter1++]+" "); for(int j=n/2+marker+1;j<n;j++) out.print(even[counter2++]+" "); out.println(); marker--; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
77b3f03036e3385afc2c62994dbd1eb1
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayDeque; import java.util.NoSuchElementException; import java.util.Queue; import static java.lang.Math.*; public class Main { public static void main(String[] args) { FastScanner fs = new FastScanner(); int n = fs.nextInt(); boolean[][] isOdd = new boolean[n][n]; final int c = (n - 1) / 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { isOdd[i][j] = min(abs(i - c), abs(j - c)) % 2 == 0; } } Queue<Integer> odds = new ArrayDeque<>(); Queue<Integer> evens = new ArrayDeque<>(); for (int i = 1; i < n*n+1; i++) { if (i % 2 == 0) { evens.add(i); } else { odds.add(i); } } int[][] ans = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ans[i][j] = isOdd[i][j] ? odds.poll() : evens.poll(); } } printIntMatrix(ans); } public static void printIntMatrix(int[][] matrix) { StringBuilder sb = new StringBuilder(); for (int[] line : matrix) { for (int c : line) { sb.append(c + " "); } sb.append('\n'); } System.out.print(sb.toString()); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
ba44ac985b59cf58c0a096abdcb48906
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class q1 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int dirs[][] = { {1, 0}, {0, -1}, {-1, 0}, {0, 1} }; for (int[] arr : printSpiralTillK(dirs, n)) { for (int num : arr) { System.out.print(num + " "); } System.out.println(""); } } private static int[][] printSpiralTillK(int[][] dirs, int n) { int size = n * n; int[][] res = new int[n][n]; int[] s = new int[2]; setStart(s, n); int idx = 0, str = idx; for (int i = 0; i < n; i++) { res[0][i] = s[idx]; s[idx] += 2; idx = (idx + 1) % 2; } int d = 0, r = n, c = n; int[] pos = {0, c - 1}; int ele = (r - 1) * c; while (ele > 0) { for (int j = 1; j < r; j++) { ele--; pos[0] += dirs[d][0]; pos[1] += dirs[d][1]; if (pos[0] == n / 2 && pos[1] == n / 2) { res[pos[0]][pos[1]] = s[idx]; } else { res[pos[0]][pos[1]] = s[idx]; s[idx] += 2; idx = (idx + 1) % 2; } } r--; int temp = r; r = c; c = temp; if ((r + c - 3) % 4 == 0) { idx = (str + 1) % 2; str = idx; } d = (d + 1) % 4; } return res; } private static void setStart(int[] s, int n) { if ((n - 1) % 4 == 0) { s[0] = 1; s[1] = 2; } else if ((n - 3) % 4 == 0) { s[0] = 2; s[1] = 1; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
e062854a557f1b8f3c2ff42fd08bdfb7
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class C710B { public static void main(String[] args) { Scanner sc=new Scanner(System.in); short n=sc.nextShort(),c=2,nc=1,l=0; if(n%2==0) for (short i = 0; i < n; i++) { for (short j = 1; j <= n; j++) { System.out.print(i*n+j+" "); } System.out.println(); } else { for (short i = 0; i < n; i++) { for (int j = 0; j < n; j++) if(j<=n/2+l&&j>=n/2-l){ System.out.print(nc+" ");nc+=2;} else{System.out.print(c+" ");c+=2;} System.out.println(); if (n/2>i)l++; else l--; } } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
1cd98bc6b88a2ae4814c228b7e4396f9
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class C710B { public static void main(String[] args) { Scanner sc=new Scanner(System.in); short n=sc.nextShort(),c=2,nc=1,l=0; for (short i = 0; i < n; i++) { for (int j = 0; j < n; j++) if(j<=n/2+l&&j>=n/2-l){ System.out.print(nc+" ");nc+=2;} else{System.out.print(c+" ");c+=2;} System.out.println(); if (n/2>i)l++; else l--; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
736618581df1bd3a800c6a35e47ce476
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class templ { int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { if (arr[j] <= pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } void sort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); sort(arr, low, pi-1); sort(arr, pi+1, high); } } public static void main(String[] args) throws FileNotFoundException { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); templ ob=new templ(); int n=in.nextInt(); int m[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { m[i][j]=0; } } int k=1; int x=0; int y=n/2; while(k<=n*n) { m[x][y]=k; k++; if(x==0&&y==n-1) { x=1; y=n-1; } else if(x==0&&y!=n-1) { x=n-1; y++; } else if(x!=0&&y==n-1) { x--; y=0; } else if(m[x-1][y+1]!=0) { x++; } else { x--; y++; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { out.print(m[i][j]+" "); } out.println(); } out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
c5251c18d85937bd5a6dc66d9db553c9
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int odd=1; int even=2; int x=1; if(n==1) System.out.println(1); else {for (int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(j<=n/2+i &&j >=n/2-i && i<=n/2) {System.out.print(odd+" "); odd+=2;} else{ if(j>=x &&j<=n-1-x &&i>n/2) {System.out.print(odd+" "); odd+=2; } else { System.out.print(even+" "); even+=2; }} } if(i>n/2) x++; System.out.println(); } } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
a4c1c1d59e4b6762df2832d252369a21
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int odd=1; int even=2; int x=1; if(n==1) System.out.println(1); else {for (int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(j<=(n/2)+i &&j >=(n/2)-i && i<=n/2) {System.out.print(odd+" "); odd+=2;} else{ if(j>=x &&j<=n-1-x &&i>n/2) {System.out.print(odd+" "); odd+=2; } else { System.out.print(even+" "); even+=2; }} } if(i>n/2) x++; System.out.println(); } } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
c05c6a244bce30a367be9e3ac60a2248
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.close(); int limit = N*N; int[][] mat = new int[N][N]; int idx = 0; ArrayList<Integer> odd = new ArrayList<>(); ArrayList<Integer> even = new ArrayList<>(); for(int i = 1 ; i <= N*N ; i+=2){ odd.add(i); if(i!=N*N) even.add(i+1); } for(int i = 0 ; i < N ; i++){ mat[i][N/2] = odd.get(idx); idx++; } for(int i = 0 ; i < N ; i++){ if(mat[N/2][i] ==0 ){ mat[N/2][i] = odd.get(idx); idx++; } } if(idx < odd.size()){ int left = odd.size() - idx; int cols = left/(N-1); if(cols%2 == 0){ for(int i = 0 ; i< N ; i++){ for(int j = 0 ; j < N ; j++){ if(mat[i][j] == 0){ mat[i][j] = odd.get(idx); idx++; } } if(idx == odd.size()) break; } } else{ // System.out.println(idx + " " + odd.size()); if(idx != (odd.size()-N + 1)){ for(int i = 0 ; i< N ; i++){ for(int j = 0 ; j < N ; j++){ if(mat[i][j] == 0){ mat[i][j] = odd.get(idx); idx++; } } if(idx == (odd.size()- N + 1)) break; } } // System.out.println(idx + " " + odd.size() + " left"); for(int i = N-1 ; i>=0 ; i--){ for(int j = N-1 ; j >= N/2 ; j--){ if(mat[i][j] == 0){ mat[i][j] = odd.get(idx); idx++; } } if(idx == odd.size()) break; } } } idx = 0; for(int i = 0 ; i < N ; i++){ for(int j = 0 ; j < N ; j++){ if(mat[i][j] == 0){ mat[i][j] = even.get(idx); idx++; } } } for(int i = 0 ; i < N ; i++){ for(int j = 0 ; j < N ; j++){ System.out.print(mat[i][j] + " "); } System.out.println(); } } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
8edf2cf41d03d369ba107e3cee7661d7
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
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.Collections; import java.util.HashSet; import java.util.StringTokenizer; import java.math.BigInteger; public class oddsqr { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { try{ FastReader s=new FastReader(); int n=s.nextInt(); int a[][]=new int[n][n]; int p = (int)(n/2); int m=(n-1)/2; int g=(m%2); if(g==1) { int k=2; int h=1; for(int i=0;i<n;i++) { if(i==p) {} else{ for(int j=0;j<n;j=j+2) { a[i][j]=k; k=k+2; } } } for(int i=0;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=1;j<n;j=j+2) { a[i][j]=h; h=h+2; } } } } else { int k=2; int h=1; int kk=p; int kt=(p+1); int hh=1; int gg=n-1; int kl=(p-1); int tt=(p+2); int ty=1; int ll=(n-1); for(int i=0;i<p;i++) { for(int j=0;j<kk;j++) { a[i][j]=k; k=k+2; } kk--; } for(int i=0;i<p;i++) { for(int j=kt;j<n;j++) { a[i][j]=k; k=k+2; } kt++; } for(int i=(p+1);i<n;i++) { for(int j=0;j<hh;j++) { a[i][j]=k; k=k+2; } hh++; } for(int i=(p+1);i<n;i++) { for(int j=gg;j<n;j++) { a[i][j]=k; k=k+2; } gg--; } for(int i=1;i<p;i++) { for(int j=kl;j<p;j++) { a[i][j]=h; h=h+2; } kl--; for(int j=(p+1);j<tt;j++) { a[i][j]=h; h=h+2; } tt++; } for(int i=p;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=ty;j<p;j++) { a[i][j]=h; h=h+2; } ty++; for(int j=(p+1);j<ll;j++) { a[i][j]=h; h=h+2; } ll--; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if( i!=p && j==p) { a[i][j]=h; h=h+2; } } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } catch(Exception e) {return;} } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
1e176a2f99a1bcb1a892f38d4e9c6314
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; public class oddsqr2 { public static void main(String args[]) { try{ Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[][]=new int[n][n]; int p = (int)(n/2); int m=(n-1)/2; int g=(m%2); if(g==1) { int k=2; int h=1; for(int i=0;i<n;i++) { if(i==p) {} else{ for(int j=0;j<n;j=j+2) { a[i][j]=k; k=k+2; } } } for(int i=0;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=1;j<n;j=j+2) { a[i][j]=h; h=h+2; } } } } else { int k=2; int h=1; int kk=p; int kt=(p+1); int hh=1; int gg=n-1; int kl=(p-1); int tt=(p+2); int ty=1; int ll=(n-1); for(int i=0;i<p;i++) { for(int j=0;j<kk;j++) { a[i][j]=k; k=k+2; } kk--; } for(int i=0;i<p;i++) { for(int j=kt;j<n;j++) { a[i][j]=k; k=k+2; } kt++; } for(int i=(p+1);i<n;i++) { for(int j=0;j<hh;j++) { a[i][j]=k; k=k+2; } hh++; } for(int i=(p+1);i<n;i++) { for(int j=gg;j<n;j++) { a[i][j]=k; k=k+2; } gg--; } for(int i=1;i<p;i++) { for(int j=kl;j<p;j++) { a[i][j]=h; h=h+2; } kl--; for(int j=(p+1);j<tt;j++) { a[i][j]=h; h=h+2; } tt++; } for(int i=p;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=ty;j<p;j++) { a[i][j]=h; h=h+2; } ty++; for(int j=(p+1);j<ll;j++) { a[i][j]=h; h=h+2; } ll--; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if( i!=p && j==p) { a[i][j]=h; h=h+2; } } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } catch(Exception e) {return;} } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
b13bd049abb54ab15d010ae34d301901
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.Scanner; public class oddsqr2 { public static void main(String args[]) { try{ Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[][]=new int[n][n]; int p = (int)(n/2); int m=(n-1)/2; int g=(m%2); if(g==1) { int k=2; int h=1; for(int i=0;i<n;i++) { if(i==p) {} else{ for(int j=0;j<n;j=j+2) { a[i][j]=k; k=k+2; } } } for(int i=0;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=1;j<n;j=j+2) { a[i][j]=h; h=h+2; } } } } else { int k=2; int h=1; int kk=p; int kt=(p+1); int hh=1; int gg=n-1; int kl=(p-1); int tt=(p+2); int ty=1; int ll=(n-1); for(int i=0;i<p;i++) { for(int j=0;j<kk;j++) { a[i][j]=k; k=k+2; } kk--; } for(int i=0;i<p;i++) { for(int j=kt;j<n;j++) { a[i][j]=k; k=k+2; } kt++; } for(int i=(p+1);i<n;i++) { for(int j=0;j<hh;j++) { a[i][j]=k; k=k+2; } hh++; } for(int i=(p+1);i<n;i++) { for(int j=gg;j<n;j++) { a[i][j]=k; k=k+2; } gg--; } for(int i=1;i<p;i++) { for(int j=kl;j<p;j++) { a[i][j]=h; h=h+2; } kl--; for(int j=(p+1);j<tt;j++) { a[i][j]=h; h=h+2; } tt++; } for(int i=p;i<n;i++) { if(i==p) { for(int j=0;j<n;j++) { a[i][j]=h; h=h+2; } } else{ for(int j=ty;j<p;j++) { a[i][j]=h; h=h+2; } ty++; for(int j=(p+1);j<ll;j++) { a[i][j]=h; h=h+2; } ll--; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if( i!=p && j==p) { a[i][j]=h; h=h+2; } } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } catch(Exception e) {return;} } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
086a2e3a13b5d3b7e500de979d198eae
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int odd = 0, even = 1; int arr[][] = new int[n][n]; StringBuilder sb = new StringBuilder(); if(n>1){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(arr[i][j]!=0) continue; if(j<n/2 && even*2<=n*n){ arr[i][j] = even++*2; arr[i][n-1-j] = even++*2; arr[n-1-i][j] = even++*2; arr[n-1-i][n-1-j] = even++*2; } else{ arr[i][j] = odd++*2+1; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ sb.append(arr[i][j]+" "); } sb.append("\n"); } } else{ sb.append(1); } System.out.print(sb); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
6b944e0ed129d4352102d4b61a0885cc
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.util.*; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int odd = 0, even = 1; int arr[][] = new int[n][n]; StringBuilder sb = new StringBuilder(); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(arr[i][j]!=0) continue; if(j<n/2 && even*2<=n*n){ arr[i][j] = even++*2; arr[i][n-1-j] = even++*2; arr[n-1-i][j] = even++*2; arr[n-1-i][n-1-j] = even++*2; } else{ arr[i][j] = odd++*2+1; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ sb.append(arr[i][j]+" "); } sb.append("\n"); } System.out.print(sb); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
58479e2b150e917628937514d6171f0e
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; // the difference (in each row/column/main diagonal) // between the number of odds and the number of evens should be an odd number. /* 0 1 0 1 1 1 0 1 0 . . 1 . . . 1 1 1 . 1 1 1 1 1 . 1 1 1 . . . 1 . . . . . 1 . . . . . 1 1 1 . . . 1 1 1 1 1 . 1 1 1 1 1 1 1 . 1 1 1 1 1 . . . 1 1 1 . . . . . 1 . . . 7*7 = 49 upper(49/2) = 25 */ public class C { static void solve(int N) throws IOException { int [][] M = new int[N][N]; int begC = N/2; int endC = N/2; int currOdd = 1; boolean increase = true; for(int r=0; r<N; r++) { for(int c=begC; c<=endC; c++) { //System.out.println("r: " + r + " c: " + c); M[r][c] = currOdd; currOdd += 2; } if(begC == 0) { increase = false; } if(increase) { begC -= 1; endC += 1; } else { begC += 1; endC -= 1; } } int currEven = 2; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); for(int r=0; r<N; r++) { for(int c=0; c<N; c++) { if(M[r][c] == 0) { M[r][c] = currEven; currEven += 2; } if(c > 0) { bw.write(" " + M[r][c]); } else { bw.write("" + M[r][c]); } } bw.newLine(); } bw.close(); } public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); solve(N); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output
PASSED
9555781e5f27dfe5ea3523d044690e98
train_002.jsonl
1471875000
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; public class magicoddsquare { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); int n = Integer.parseInt(r.readLine()); PriorityQueue<Integer> odd = new PriorityQueue<Integer>(); PriorityQueue<Integer> even = new PriorityQueue<Integer>(); for (int i = 1; i <= n * n; i++) { if (i % 2 == 1) { odd.add(i); } else even.add(i); } for (int i = 0; i < n / 2; i++) { for (int j = 0; j < (n / 2) - i; j++) { w.print(even.remove() + " "); } for (int j = 0; j < 2 * i + 1; j++) { w.print(odd.remove() + " "); } for (int j = 0; j < (n / 2) - i; j++) { w.print(even.remove() + " "); } w.println(); } for (int i = 0; i < n; i++) { w.print(odd.remove() + " "); } w.println(); for (int i = n/2 - 1; i >= 0; i--) { for (int j = 0; j < (n / 2) - i; j++) { w.print(even.remove() + " "); } for (int j = 0; j < 2 * i + 1; j++) { w.print(odd.remove() + " "); } for (int j = 0; j < (n / 2) - i; j++) { w.print(even.remove() + " "); } w.println(); } w.flush(); } }
Java
["1", "3"]
1 second
["1", "2 1 4\n3 5 7\n6 9 8"]
null
Java 8
standard input
[ "constructive algorithms", "math" ]
a7da19d857ca09f052718cb69f2cea57
The only line contains odd integer n (1 ≤ n ≤ 49).
1,500
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
standard output