exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
7ae3982e57da2765c6fa0e560ba3c2d7
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class A { static MyScanner in = new MyScanner(); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static long H,W; static BitSet bs; static long mod = 1000000007; // All possible moves of a knight static int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; static int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; public static void main(String args[]) throws IOException { /** 1.What is the unknown: 2.What are the data: 3.What is the condition: 4.What is the restriction: 5. understand the problem: 6. What are the cases edges in the problem: */ int n = in.nextInt(); int m = in.nextInt(); ArrayList<Integer> a = new ArrayList<>(2000000); for(int i=0;i<n;i++){ a.add( in.nextInt()); } Collections.sort(a); int sum =0; for(int j=0;j<m;j++){ int k= in.nextInt(); int val = lowerBound(k+1, a); out.print(val+" "); } out.flush(); } static int lowerBound(int val, ArrayList<Integer> a){ int mid = 0; int lo =0; int hi = a.size(); while(lo<hi){ mid = (lo+hi)>>1; if(a.get(mid)<val){ lo = mid+1; }else{ hi = mid; } } return lo; } static boolean isVowel(char c){ if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='y'){ return true; } return false ; } static class IP implements Comparable<IP>{ public int first,second; IP(int first, int second){ this.first = first; this.second = second; } public int compareTo(IP ip){ if(first==ip.first) return second-ip.second; return first-ip.first; } } static long gcd(long a, long b){ return b!=0?gcd(b, a%b):a; } static boolean isEven(long a) { return (a&1)==0; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109). The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
6b889e13310beed9ff29b12000644c97
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.PriorityQueue; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] arr1 = new int[n]; int[] arr2 = new int[m]; for (int i = 0; i < arr1.length; i++) { arr1[i] = sc.nextInt(); } for (int i = 0; i < arr2.length; i++) { arr2[i] = sc.nextInt(); } StringBuilder sb = new StringBuilder(); PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 0; i < arr1.length; i++) { pq.add(arr1[i]); } int c = 0; while (!pq.isEmpty()) { arr1[c++] = pq.poll(); } for (int i = 0; i < arr2.length; i++) { int number = binarySearch(arr1, arr2[i]); sb.append(number + " "); } System.out.println(sb); } public static int binarySearch(int[] arr1, int n) { int start = 0; int end = arr1.length - 1; while (start + 1 < end) { int mid = (start + end) / 2; if (arr1[mid] > n) { end = mid - 1; } else { start = mid; } } if (arr1[end] <= n) { return end + 1; } if (arr1[start] <= n) { return start + 1; } return 0; } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109). The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
7c81eaa3751d883713fa71094e07ef69
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] arr1 = new int[n]; int[] arr2 = new int[m]; for (int i = 0; i < arr1.length; i++) { arr1[i] = sc.nextInt(); } for (int i = 0; i < arr2.length; i++) { arr2[i] = sc.nextInt(); } StringBuilder sb = new StringBuilder(); PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 0; i < arr1.length; i++) { pq.add(arr1[i]); } int c = 0; while (!pq.isEmpty()) { arr1[c++] = pq.poll(); } //Arrays.sort(arr1); for (int i = 0; i < arr2.length; i++) { int number = binarySearch(arr1, arr2[i]); sb.append(number + " "); } System.out.println(sb); } public static int binarySearch(int[] arr1, int n) { int start = 0; int end = arr1.length - 1; while (start + 1 < end) { int mid = (start + end) / 2; if (arr1[mid] > n) { end = mid - 1; } else { start = mid; } } if (arr1[end] <= n) { return end + 1; } if (arr1[start] <= n) { return start + 1; } return 0; } // private static int binarySearch(int[] arr1, int n, int start, int end) { //// if (start > end) { //// return -1; //// } // int mid = (start + end) / 2; // if (arr1[mid] <= n && arr1[mid + 1] > n) { // return mid + 1; // } // if (arr1[mid] > n) { // return binarySearch(arr1, n, start, mid - 1); // } // return binarySearch(arr1, n, mid, end); // } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109). The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
01e2c813cbd2e14fecd9b3cf05f4c68e
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod=(long)(1e9+7); static double PI=3.1415926535; public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer s=new StringTokenizer(br.readLine()); int n=Integer.parseInt(s.nextToken()); int m=Integer.parseInt(s.nextToken()); int a[]=new int[n]; int b[]=new int[m]; s=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s.nextToken()); } s=new StringTokenizer(br.readLine()); for(int i=0;i<m;i++) { b[i]=Integer.parseInt(s.nextToken()); } shuffleArray(a); Arrays.sort(a); int ans[]=new int[m]; for(int i=0;i<b.length;i++) { ans[i]=bs(b[i],a)+1; } for(int i:ans){ pw.print(i+" "); } pw.close(); } private static int bs(int val, int[] a) { int lo=0; int hi=a.length; int ans=-1; while(lo<hi) { int mid=(lo+hi)/2; if(a[mid]<=val) { lo=mid+1; ans=mid; }else { hi=mid; } } return ans; } static void shuffleArray(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109). The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
ea43fcf62776c90fa912ca6d03f04618
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.List; import java.util.Objects; import java.util.TreeMap; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Main { public void exec() { int n = stdin.nextInt(); int m = stdin.nextInt(); int[] a = stdin.nextIntArray(n); int[] b = stdin.nextIntArray(m); TreeMap<Integer, Long> t = new TreeMap<>(Arrays.stream(a).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))); List<Integer> keys = t.keySet().stream().sorted().collect(Collectors.toList()); for (int i = 0; i < keys.size()-1; i++) { t.put(keys.get(i+1), t.get(keys.get(i+1)) + t.get(keys.get(i))); } int[] c = new int[m]; for (int i = 0; i < m; i++) { Integer k = t.floorKey(b[i]); if (k == null) { c[i] = 0; } else { c[i] = t.get(k).intValue(); } } stdout.println(Arrays.stream(c).mapToObj(Integer::toString).collect(Collectors.joining(" "))); } private static final Stdin stdin = new Stdin(); private static final Stdout stdout = new Stdout(); public static void main(String[] args) { new Main().exec(); stdout.flush(); } public static class Stdin { private BufferedReader stdin; private Deque<String> tokens; private Pattern delim; public Stdin() { stdin = new BufferedReader(new InputStreamReader(System.in)); tokens = new ArrayDeque<>(); delim = Pattern.compile(" "); } public String nextString() { try { if (tokens.isEmpty()) { String line = stdin.readLine(); delim.splitAsStream(line).forEach(tokens::addLast); } return tokens.pollFirst(); } catch (IOException e) { throw new UncheckedIOException(e); } } public int nextInt() { return Integer.parseInt(nextString()); } public double nextDouble() { return Double.parseDouble(nextString()); } public long nextLong() { return Long.parseLong(nextString()); } public String[] nextStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = nextString(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } public static class Stdout { private PrintWriter stdout; public Stdout() { stdout = new PrintWriter(System.out, false); } public void printf(String format, Object ... args) { stdout.printf(format, args); } public void println(Object ... objs) { String line = Arrays.stream(objs).map(this::deepToString).collect(Collectors.joining(" ")); stdout.println(line); } private String deepToString(Object o) { if (o == null || !o.getClass().isArray()) { return Objects.toString(o); } int len = Array.getLength(o); String[] tokens = new String[len]; for (int i = 0; i < len; i++) { tokens[i] = deepToString(Array.get(o, i)); } return "{" + String.join(",", tokens) + "}"; } public void flush() { stdout.flush(); } } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” the elements of array a ( - 109 ≀ ai ≀ 109). The third line contains m integers β€” the elements of array b ( - 109 ≀ bj ≀ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
5adc0e59b0777302ba71e5c2bfe781ac
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; public class test { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String line1 = keyboard.nextLine(); String line2 = keyboard.nextLine(); if (line1.equals(line2)) System.out.println(-1); else System.out.println(Math.max(line1.length(), line2.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
831ebdca8fc961fa3514d1319503a8b4
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; import java.lang.String; public class first{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s1=sc.nextLine(); String s2=sc.nextLine(); int l1=s1.length(); int l2=s2.length(); if(s1.compareTo(s2)==0){ System.out.println("-1"); return; } if(l1>l2){ System.out.println(l1); return; } else { System.out.println(l2); } return; } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
1ccfc0fa07b6dd935ccc92131618bcbb
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws Throwable { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String a=in.readLine(); String b=in.readLine(); if(a.equals(b)) { System.out.println(-1); } else System.out.println(Math.max(a.length(), b.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
fbc4c08b171692048751ee5b05132e6a
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws Throwable { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String a=in.readLine(); String b=in.readLine(); if(a.equals(b)) { int i=0; for(;i<a.length();i++) if(a.charAt(i)!=b.charAt(i)) { System.out.println(a.length()-1); break; } if(i==a.length()) System.out.println(-1); } else System.out.println(Math.max(a.length(), b.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
00fada19349e87600bcc9083c2659f25
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class CFA { static String max, min ; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for(String ln;(ln=in.readLine())!=null;){ String a = ln; String b = in.readLine(); if(a.equals(b)) System.out.println(-1); else{ max = a.length()>b.length()?a:b; min = a.length()<b.length()?a:b; System.out.println(max.length()); } } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
d89c5ef07d1b3b97f68dbc89327f39d7
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class A { static String a, b; public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); a = in.readLine(); b = in.readLine(); int asw = 0; if (a.length() != b.length()) { /*int T[] = getBorderArray(a.toCharArray()); asw = indexOf(b.toCharArray(), a.toCharArray(), T); System.out.println(asw); System.out.println(asw==-1?a.length():-1);*/ System.out.println(Math.max(a.length(), b.length())); } else { int T[] = getBorderArray(b.toCharArray()); asw = indexOf(a.toCharArray(), b.toCharArray(), T); System.out.println(asw==-1?b.length():-1); } } static int[] getBorderArray(char[] W) { int[] T = new int[W.length + 1]; T[0] = -1; T[1] = 0; for (int i = 2, j = 0; i <= W.length;) { if (W[i - 1] == W[j]) T[i++] = ++j; else if (j > 0) j = T[j]; else T[i++] = 0; } return T; } static int indexOf(char[] S, char[] W, int[] T) { // Índice donde ocurre S // en W. // T=getBorderArray(W). if (S.length == 0) return 0; for (int m = 0, i = 0; m + i < W.length;) { if (S[i] == W[m + i]) { if (++i == S.length) return m; } else { m += i - T[i]; if (i > 0) i = T[i]; } } return -1; } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
0f5d98c2bc197db22e40ffaca5849858
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; public class Codeforces4 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String a = sc.next(); String b = sc.next(); if(a.equals(b)){ System.out.println("-1"); }else { int result = Math.max(a.length(), b.length()); System.out.println(result); } sc.close(); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
419258003171ccb03b1448eb00a4eba5
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.Scanner; public class GfG{ public static void main(String[] args){ Scanner sc=new Scanner (System.in); String s=sc.next(); String s1=sc.next(); if(s.equals(s1)){ System.out.println("-1"); } else{ System.out.println(s.length()>s1.length()?s.length():s1.length()); } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
92e7537428e3945c82f2e0d678515ec5
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; import java.lang.Math; import java.util.Arrays; import java.util.Scanner; import java.util.stream.IntStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; public class Problem { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { String a = in.next(); String b = in.next(); if(a.length()>=b.length()){ if(a.contains(b) && b.contains(a)){ out.print("-1"); return; } else{ out.print(a.length()); } } else{ if(b.contains(a) && a.contains(b)){ out.print("-1"); return; } else{ out.print(b.length()); return; } } } } public int factorial(int n) { int fact = 1; int i = 1; while(i <= n) { fact *= i; i++; } return fact; } public static int BinarySearch(long temp,long[] sum,int r) { int l=0; while(l<=r) { int mid=l+(r-l)/2; if(sum[mid]==temp&&sum[mid]!=-1) { return mid; } if(sum[mid]>temp&&sum[mid]!=-1) r=mid-1; if(sum[mid]<temp&&sum[mid]!=-1) l=mid+1; } return -1; } public static long gcd(long x,long y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b) { return (int)Math.abs(a-b); } public static long abs(long a,long b) { return (long)Math.abs(a-b); } public static int max(int a,int b) { if(a>b) return a; else return b; } public static int min(int a,int b) { if(a>b) return b; else return a; } public static long max(long a,long b) { if(a>b) return a; else return b; } public static long min(long a,long b) { if(a>b) return b; else return a; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static long sort(int a[]){ int n=a.length; int b[]=new int[n]; return mergeSort(a,b,0,n-1); } static long mergeSort(int a[],int b[],long left,long right){ long c=0; if(left<right){ long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right){ long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right){ if(a[i]<=a[j]){ b[k++]=a[i++]; } else{ b[k++]=a[j++];c+=mid-i; } } while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
8cea74d714e7b4ab1ca90e30c2565a14
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.*; public class Main { public static void main(String args[])throws IOException { BufferedReader obj=new BufferedReader(new InputStreamReader(System.in)); String a=obj.readLine(); String b=obj.readLine(); //int dp[][]=new int[a.length()+1][b.length()+1]; //for(int i=1;i<=a.length();i++) //{ // for(int j=1;j<=b.length();j++) // { // if(a.charAt(i-1)==b.charAt(j-1)) // { // dp[i][j]=dp[i-1][j-1]+1; // } // else // { // dp[i][j]=Math.max(dp[i-1][j],Math.max(dp[i-1][j-1],dp[i][j-1])); // } // } //} if(a.length()!=b.length()) System.out.println(Math.max(a.length(), b.length())); else if(a.equals(b)) System.out.println(-1); else System.out.println(a.length()); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
f37ef1866c3680bbced4b973d74ef9ea
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1=in.next(); String s2=in.next(); if(s1.equals(s2)) System.out.println(-1); else System.out.println(Integer.max(s1.length(), s2.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
bb709882bdc0e26b05252bd7d0d3c31c
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; public class Test{ public static void main(String args[]) throws Exception { Scanner st=new Scanner(System.in); String s1=st.next().trim(); String s2=st.next().trim(); if(s1.equals(s2)){ System.out.println("-1"); }else{ System.out.println(Math.max(s1.length(),s2.length())); } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
ebb3c9a9aa9de09b05bbdf4ae5bfa429
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
//package excerciseA; import java.io.Console; import java.util.Scanner; public class aExcercise { public static void main(String[] args){ Scanner input = new Scanner(System.in); String a = input.nextLine(); String b = input.nextLine(); while(true){ if(a.isEmpty() || b.isEmpty()){ System.out.println("Cannot have empty strings"); a = input.next(); b = input.next(); } else if(a.length()>100000 || b.length() > 100000){ System.out.println("Cannot exceed this 10^5 digits"); a = input.next(); b = input.next(); } else{ break; } } int result = checkLengths(a, b); System.out.println(result); } private static int checkLengths(String a, String b){ if(a.length() > b.length()){ return a.length(); } else if(a.length() < b.length()){ return b.length(); } else{ if(a.equals(b) ){ return -1; }else{ return a.length(); } } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
edd9410660ab3a6f1c225ef8bee8ac75
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
//package excerciseA; import java.io.Console; import java.util.Scanner; public class aExcercise { public static void main(String[] args){ Scanner input = new Scanner(System.in); String a = input.nextLine(); String b = input.nextLine(); while(true){ if(a.isEmpty() || b.isEmpty()){ System.out.println("Cannot have empty strings"); a = input.next(); b = input.next(); } else if(a.length()>100000 || b.length() > 100000){ System.out.println("Cannot exceed this 10^5 digits"); a = input.next(); b = input.next(); } else{ break; } } int result = checkLengths(a, b); System.out.println(result); } private static int checkLengths(String a, String b){ if(a.length() > b.length()){ return a.length(); } else if(a.length() < b.length()){ return b.length(); } else{ if(a.equals(b) ){ return -1; }else{ return a.length(); } } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
82746a7d02dfcce5c9c23435b23e8ad3
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package acm; import java.util.*; import java.io.*; import java.util.Scanner; import java.io.IOException; /** * * @author bro2 */ public class Acm { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String a,b; a = sc.next(); b = sc.next(); int sizea = a.length(); int sizeb = b.length(); //System.out.println(sizea + " " + sizeb); if (sizea > sizeb ){ System.out.println(sizea); } if(sizea < sizeb){ System.out.println(sizeb); } if((sizea == sizeb) &&(a.equals(b))) { System.out.println(-1); } else if (sizea == sizeb){ System.out.println(sizea); } } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
2979f69bc59a1c0a0ce7615ad7054164
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class MahmoudLongestUncommonSubsequence { public static PrintWriter out = new PrintWriter(System.out); public static Scanner in = new Scanner(System.in); public static void main(String[] args) { // int t = ni(); // while (t-- > 0) solve(); out.flush(); } static int max = 0; private static void solve() { char[] a = in.next().toCharArray(); char[] b = in.next().toCharArray(); if (!Arrays.equals(a, b)) { out.println(Math.max(a.length, b.length)); } else { out.println("-1"); } } private static int ni() { return in.nextInt(); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static long nl() { return in.nextLong(); } private float nf() { return in.nextFloat(); } private static double nd() { return in.nextDouble(); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
151c99218a89562972aefd89dddcc492
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class MahmoudLongestUncommonSubsequence { public static PrintWriter out = new PrintWriter(System.out); public static Scanner in = new Scanner(System.in); public static void main(String[] args) { // int t = ni(); // while (t-- > 0) solve(); out.flush(); } static int max = 0; private static void solve() { char[] a = in.next().toCharArray(); char[] b = in.next().toCharArray(); if (!Arrays.equals(a,b)){ out.println(Math.max(a.length,b.length)); return; } max = 0; int len = 0; int j = 0; for (char c : b) { if (j < a.length && a[j] == c) { len = 0; j++; } else { j = 0; len++; } max = Math.max(max, len); } out.println(max == 0 ? -1 : max); } private static void cal(char[] a, char[] b, int i, int j, int len) { if (i >= a.length || j >= b.length) return; if (a[i] != b[j]) { max = Math.max(max, len + 1); cal(a, b, i + 1, j + 1, len + 1); } else { cal(a, b, i, j + 1, 0); cal(a, b, i + 1, j, 0); } } private static int ni() { return in.nextInt(); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static long nl() { return in.nextLong(); } private float nf() { return in.nextFloat(); } private static double nd() { return in.nextDouble(); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
ccb8908334430c63bfc4c555f1e8fd49
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class a { Scanner sc; PrintWriter out; void solve(){ //Enter code here utkarsh String a,b; a=sc.next(); b=sc.next(); if(a.compareTo(b)==0){ out.println("-1"); }else{ out.println(Math.max(a.length(),b.length())); } } public static void main(String[] args) { new a().run(); } void run(){ sc=new Scanner(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
c30d184705c072f7834db87da936456a
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * @author MiloMurphy */ public class LUCS { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader in = new FastReader(); public static void main(String[] args) { int t = 1; // in.nextInt(); while (t-- > 0) { solve(); } } public static void solve() { String a = in.next(); String b = in.next(); System.out.println((a.equals(b)? -1:max(a.length(), b.length()))); } public static int max(int a, int b) { return a > b ? a : b; } public static int min(int a, int b) { return a < b ? a : b; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, (a % b)); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
94eb670782f758e50ae6eeb81cc2efbd
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String a,b; a=input.next(); b=input.next(); if(a.equals(b)) System.out.println(-1); else if(a.length()>b.length()) System.out.println(a.length()); else System.out.println(b.length()); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
a1b758848e43da8b832e984205309e12
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.next(); String s2 = in.next(); System.out.println(s1.equals(s2) ? -1 : Math.max(s1.length(), s2.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
4869bf6d3e77b04b52ade9f61882407a
train_000.jsonl
1486487100
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
256 megabytes
import java.util.*; public class Sub { public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.next(); String b = in.next(); System.out.println(a.equals(b) ? -1 : Math.max(a.length(), b.length())); } }
Java
["abcd\ndefgh", "a\na"]
2 seconds
["5", "-1"]
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
Java 8
standard input
[ "constructive algorithms", "strings" ]
f288d7dc8cfcf3c414232a1b1fcdff3e
The first line contains string a, and the second lineΒ β€” string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
1,000
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
standard output
PASSED
fad9f65330e44fc349f668ca029e706f
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { String s=next(); String t=next(); int tn=t.length(); int[]A=new int[tn]; for (int i=0;i<tn;i++) { if (t.charAt(i)=='1') A[i]=1; //h=(h*3+A[i])%mod; } long h=0; long g=0; long mult=1; ArrayList<Integer>C=new ArrayList(); for (int i=0;i<tn-1;i++) { h=(h*3+A[i])%mod; g=(g+mult*A[tn-1-i])%mod; mult=(mult*3)%mod; if (g==h) C.add(i+1); //out.println(i+" "+h+" "+g); } int over=0; for (int i=C.size()-1;i>=0;i--) { int u=C.get(i); //out.println(u); boolean f=true; for (int p=0,q=tn-u;p<u;p++,q++) { if (A[p]!=A[q]) { f=false; break; } } if (f) { over=u; break; } } //out.println(over); int one=0; int zero=0; for (int i=0;i<s.length();i++) { if (s.charAt(i)=='1') one++; else zero++; } int ct=0; int p=0; while (ct<s.length()) { if (A[p]==1) { if (one>0) { out.print(1); one--; } else break; } else { if (zero>0) { out.print(0); zero--; } else break; } ct++; p++; if (p==tn) p=over; } while (one>0) { out.print(1); one--; } while (zero>0) { out.print(0); zero--; } out.println(); out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
fb0d8f3fa4d8ee9a99c6c3ae3588487b
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(1, scan, out); out.close(); } static class Task { static long[][] exp; static char[] s; static char[] t; static int[] val = {7, 13}; static long[] MOD = {17, 23, 57, 107, 109, 217, 651}; public void solve(int testNumber, FastReader scan, PrintWriter out) { s = scan.next().toCharArray(); t = scan.next().toCharArray(); exp = new long[t.length+1][MOD.length]; for(int i = 0; i <= t.length; i++) { for(int j = 0; j < MOD.length; j++) { if(i == 0) exp[i][j] = 1; else exp[i][j] = mult(exp[i-1][j], 2, MOD[j]); } } int minLen = t.length-findMax(), at = 0; int[] count = new int[2]; for(int i = 0; i < s.length; i++) count[s[i]-'0']++; for(int i = 0; i < s.length; i++) { int need = t[at]-'0'; if(count[need] == 0) need ^= 1; count[need]--; out.print(need); at = (int) add(at, 1, minLen); } } static int findMax() { RollingHash start = new RollingHash(), end = new RollingHash(); int max = 0; for(int i = 0; i < t.length/2; i++) { start.addLast(t[i]-'0'); end.addFirst(t[t.length-i-1]-'0'); if(start.check(end)) max = i+1; } return max; } static long mult(long a, long b, long mod) { return ((a%mod)*(b%mod))%mod; } static long add(long a, long b, long mod) { return (a%mod+b%mod)%mod; } static class RollingHash { int size = 0; long[] value = new long[MOD.length]; public void addFirst(int v) { for(int i = 0; i < value.length; i++) { value[i] = add(value[i], mult(val[v], exp[size][i], MOD[i]), MOD[i]); } size++; } public void addLast(int v) { for(int i = 0; i < value.length; i++) { value[i] = mult(value[i], 2, MOD[i]); value[i] = add(value[i], val[v], MOD[i]); } size++; } public boolean check(RollingHash other) { for(int i = 0; i < value.length; i++) { if(value[i] != other.value[i]) return false; } return true; } } } static void shuffle(int[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
e3024783f33a85ebf97bf8ef8f98d038
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(1, scan, out); out.close(); } static class Task { static long[][] exp; static char[] s; static char[] t; static int[] val = {7, 13}; static long[] MOD = {(int) 1e9+7, (int) 1e9+9, (int) 1e9+23}; public void solve(int testNumber, FastReader scan, PrintWriter out) { s = scan.next().toCharArray(); t = scan.next().toCharArray(); exp = new long[t.length+1][MOD.length]; for(int i = 0; i <= t.length; i++) { for(int j = 0; j < MOD.length; j++) { if(i == 0) exp[i][j] = 1; else exp[i][j] = mult(exp[i-1][j], 2, MOD[j]); } } int minLen = t.length-findMax(), at = 0; int[] count = new int[2]; for(int i = 0; i < s.length; i++) count[s[i]-'0']++; for(int i = 0; i < s.length; i++) { int need = t[at]-'0'; if(count[need] == 0) need ^= 1; count[need]--; out.print(need); at = (int) add(at, 1, minLen); } } static int findMax() { RollingHash start = new RollingHash(), end = new RollingHash(); int max = 0; for(int i = 0; i < t.length/2; i++) { start.addLast(t[i]-'0'); end.addFirst(t[t.length-i-1]-'0'); if(start.check(end)) max = i+1; } return max; } static long mult(long a, long b, long mod) { return ((a%mod)*(b%mod))%mod; } static long add(long a, long b, long mod) { return (a%mod+b%mod)%mod; } static class RollingHash { int size = 0; long[] value = new long[MOD.length]; public void addFirst(int v) { for(int i = 0; i < value.length; i++) { value[i] = add(value[i], mult(val[v], exp[size][i], MOD[i]), MOD[i]); } size++; } public void addLast(int v) { for(int i = 0; i < value.length; i++) { value[i] = mult(value[i], 2, MOD[i]); value[i] = add(value[i], val[v], MOD[i]); } size++; } public boolean check(RollingHash other) { for(int i = 0; i < value.length; i++) { if(value[i] != other.value[i]) return false; } return true; } } } static void shuffle(int[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
d0da0da0fe218530d5172ca8a9fcbb6a
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.*; import java.util.*; public class D_CampSchedule { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } private static class Solver { private void solve(InputReader inp, PrintWriter out) { String s = inp.next(); String t = inp.next(); int k = t.length() - 1; RollingHash left = new RollingHash(500001); RollingHash right = new RollingHash(500001); // minimum characters needed from the back int min = t.length(); //left gets characters from the back //right gets charactes form the front for (int i = 0; i < t.length() - 1; i++) { left.addFirst(t.charAt(k - i)); right.addLast(t.charAt(i)); if (left.hash == right.hash && equal(left.hashedString, right.hashedString)) { min = k - i; } } int costEA = 0, costEB = 0; for (int i = 0; i < min; i++) { if (t.charAt(k - i) == '0') costEA++; else costEB++; } int costSA = 0, costSB = 0; for (char c: s.toCharArray()) { if (c == '0') costSA++; else costSB++; } int costTA = 0, costTB = 0; for (char c: t.toCharArray()) { if (c == '0') costTA++; else costTB++; } StringBuilder sb = new StringBuilder(); if (costTA <= costSA && costTB <= costSB) { sb.append(t); costSA -= costTA; costSB -= costTB; } String sub = t.substring(t.length() - min); while (costEA <= costSA && costEB <= costSB) { sb.append(sub); costSA -= costEA; costSB -= costEB; } while (costSA > 0) { sb.append('0'); costSA--; } while (costSB > 0) { sb.append('1'); costSB--; } out.print(sb.toString()); } private boolean equal(LinkedList<Character> a, LinkedList<Character> b) { Object[] aa = a.toArray(); Object[] ba = b.toArray(); if (aa.length != ba.length) throw new RuntimeException(); for (int i = 0; i < aa.length; i++) { if ((char) aa[i] != (char) ba[i]) return false; } return true; } public class RollingHash { //private String hashedString; private LinkedList<Character> hashedString; private long hash = 0; private final long a = 22695477; private final long m = (long) Math.pow(2, 32); private long invA; private long[] pow; private RollingHash(int n) { hashedString = new LinkedList<>(); this.invA = inverse1(a, m); pow = new long[n + 1]; pow[0] = 1; for (int i = 1; i <= n; i++) pow[i] = (pow[i - 1] * a) % m; } private void removeLast() { int n = hashedString.size() - 1; char c = hashedString.removeLast(); hash -= c * pow[n]; hash = ((hash % m) + m) % m; } private void removeFirst() { char c = hashedString.removeFirst(); hash -= c; hash *= invA; hash = ((hash % m) + m) % m; } private void addLast(char c) { int n = hashedString.size(); hash += c * pow[n]; hash = hash % m; hashedString.addLast(c); } private void addFirst(char c) { hash *= a; hash += c; hash = hash % m; hashedString.addFirst(c); } } public static long inverse1(long a, long m) { long m0 = m, y = 0, x = 1; if (m == 1) return 0; while (a > 1) { long q = a / m, t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
f29b783b7d9398a03eb7ca919d8ffe16
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class D { int[] funcZ(String two){ int[] z = new int[two.length()]; int l = 0; int r = 0; for(int i = 1;i<two.length();i++){ if(i < r){ z[i] = Math.min(r - i, z[i - l]); } while(i + z[i]< two.length() && two.charAt(i + z[i]) == two.charAt(z[i])){ z[i]++; } if(i + z[i] > r){ l = i; r = i + z[i]; } } return z; } void solve() { String one = readString(); String two = readString(); if(two.length() > one.length()){ out.print(one); return; } int[] z = funcZ(two); int num = two.length(); for(int i = 1;i<two.length();i++){ if(z[i] == two.length() - i){ num = i; break; } } int now = 0; StringBuilder ans = new StringBuilder(); for(int i = 0;i<two.length();i++){ if(two.charAt(i) == '1') now++; ans.append(two.charAt(i)); } int limit = 0; for(int i = 0;i<one.length();i++){ if(one.charAt(i) == '1') limit++; } if(now > limit || one.length() - ans.length() < limit - now){ out.print(one); return; } StringBuilder add =new StringBuilder(); int addOne = 0; for(int i = two.length() - num;i<two.length();i++){ add.append(two.charAt(i)); if(two.charAt(i) == '1') addOne++; } while(add.length() + ans.length() <= one.length() && now + addOne <= limit && one.length() - ans.length() - add.length() >= limit - now - addOne){ ans.append(add); now += addOne; } while(now < limit){ ans.append('1'); now++; } while(ans.length() < one.length()) ans.append('0'); out.print(ans); } public static void main(String[] args) { new D().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private BufferedReader in; private StringTokenizer tok = new StringTokenizer(""); private PrintWriter out; private void init() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // try { // in = new BufferedReader(new FileReader("absum.in")); // out = new PrintWriter(new File("absum.out")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } } private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } private String readString() { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
e706a825078185e6162fe05159eba1aa
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class CF1138D { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] s = br.readLine().toCharArray(); char[] t = br.readLine().toCharArray(); if(t.length==1) System.out.println(s); else { int[] ctr = new int[2]; for(int i=0; i<s.length; i++) ctr[s[i]-'0']++; long[] prefixHashes = new long[t.length]; long[] suffixHashes = new long[t.length]; int x = 256, mod = 1000000007; prefixHashes[0] = t[0]; int maxps = 0; for(int i=1; i<t.length-1; i++){ prefixHashes[i] = (x*prefixHashes[i-1]+t[i])%mod; } long[] xPows = new long[t.length]; xPows[0] = 1; for(int i=1; i<t.length; i++) { xPows[i] = (xPows[i-1]*x)%mod; } // System.out.println(Arrays.toString(xPows)); // System.out.println(prefixHashes[t.length-2]); // System.out.println(t[0]*xPows[t.length-2]); suffixHashes[1] = (x*(prefixHashes[t.length-2]-t[0]*xPows[t.length-2])+t[t.length-1])%mod; if(suffixHashes[1]<0) suffixHashes[1]+=mod; for(int i=2; i<t.length; i++){ suffixHashes[i] = (suffixHashes[i-1]-t[i-1]*xPows[t.length-i]); if(suffixHashes[i]<0) suffixHashes[i]+=mod*Math.ceil(-1.0*suffixHashes[i]/mod); } // System.out.println(Arrays.toString(prefixHashes)); // System.out.println(Arrays.toString(suffixHashes)); for(int i=0; i<t.length-1; i++) { // System.out.println(prefixHashes[i]+" "+suffixHashes[t.length-1-i]); if(prefixHashes[i]==suffixHashes[t.length-1-i] && match(t, i+1)) maxps = i+1; } // System.out.println(maxps); int i = 0; StringBuilder sb = new StringBuilder(); while(true){ if(ctr[t[i]-'0']<1) break; sb.append(t[i]); ctr[t[i]-'0']--; i++; if(i==t.length) i = maxps; } while(ctr[0]>0){ ctr[0]--; sb.append(0); } while(ctr[1]>0){ ctr[1]--; sb.append(1); } System.out.println(sb); } } static boolean match(char[] s, int len){ for(int i=0; i<len; i++) if(s[i]!=s[s.length-len+i]) return false; return true; } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
29baf28ad69414fb8007a5c34e161077
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.NoSuchElementException; public class Main{ public static void main(String[] args){ FastScanner sc = new FastScanner(); String S = sc.next(); String T = sc.next(); PrintWriter out = new PrintWriter(System.out); int o = overlap(T,T); int a = 0; int b = 0; int c = 0; int d = 0; for(int i=0;i<T.length();i++){ if(i<o){ if(T.charAt(i)=='0'){ a++; }else{ b++; } }else{ if(T.charAt(i)=='0'){ c++; }else{ d++; } } } int p = 0; int q = 0; for(int i=0;i<S.length();i++){ if(S.charAt(i)=='0'){ p++; }else{ q++; } } //System.out.println(o); if(a+c>p||b+d>q){ for(int i=0;i<p;i++){ out.print(0); } for(int i=0;i<q;i++){ out.print(1); } }else{ out.print(T); p -= a+c; q -= b+d; //System.out.println(p+" "+q); //System.out.println(c+" "+d); int f = c==0?1000000:p/c; int g = d==0?1000000:q/d; int min = Math.min(f,g); for(int i=0;i<min;i++){ out.print(T.substring(o)); } p -= c * min; q -= d * min; for(int i=0;i<p;i++){ out.print(0); } for(int i=0;i<q;i++){ out.print(1); } } out.flush(); } private static int overlap(String a, String b) { int l = a.length(); long ah1 = 0; long ah2 = 0; long ah3 = 0; long bh1 = 0; long bh2 = 0; long bh3 = 0; long t1 = 1; long t2 = 1; long t3 = 1; int A = 1000000007; int B = 1000000009; int mod = 998244353; int ans = 0; for(int i=1;i<l;i++){ ah1 = ah1 + a.charAt(l-i) * t1; ah1 %= mod; ah2 = ah2 + a.charAt(l-i) * t2; ah2 %= mod; bh1 = bh1 * A + b.charAt(i-1); bh1 %= mod; bh2 = bh2 * B + b.charAt(i-1); bh2 %= mod; if(ah1==bh1&&ah2==bh2&&ah3==bh3){ ans = i; } t1 *= A; t1 %= mod; t2 *= B; t2 %= mod; } return ans; } } class FastScanner { private final java.io.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;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public 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(); } 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() { 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 (int) (minus ? -n : n); }else{ throw new NumberFormatException(); } b = readByte(); } } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
ed8a03b28ea504a234ff947779aa0684
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class Main { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); char[] a1 = sc.nextString().toCharArray(); char[] a2 = sc.nextString().toCharArray(); int[] z = computeZArray(a2); int len = 0; for (int i = z.length - 1; i > 0; i--) { if (z.length - z[i] == i) len = Math.max(len, z[i]); } int[] cnt = new int[2]; for (char c : a1) cnt[c - '0']++; StringBuffer sb = new StringBuffer(); int i = 0; while (cnt[a2[i] - '0']-- > 0) { sb.append(a2[i] - '0'); i++; if (i == a2.length) i = len; } while (cnt[0]-- > 0) sb.append('0'); while (cnt[1]-- > 0) sb.append('1'); System.out.println(sb.toString()); } static int[] computeZArray(char[] s) { int[] z = new int[s.length]; int L = 0, R = 0; for (int i = 1; i < s.length; i++) { if (i > R) { L = R = i; while (R < s.length && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < s.length && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } } return z; } 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[][] nextInts(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public int[] nextIntArray(int n, int offset) { int[] arr = new int[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public long[] nextLongArray(int n, int offset) { long[] arr = new long[n + offset]; for (int i = 0; i < n; i++) { arr[i + offset] = 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
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
f5071785cb306f34ef8c9340d3190fb1
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable{ static class pair implements Comparable { int f; int s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(s>pr.s) return 1; if(s==pr.s) { if(f>pr.f) return 1; else return -1; } else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,t; int s; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } int[] kmpsearch(String s) { int n=s.length(); int lps[]=new int[n+1]; lps[0]=0; int border=0; for(int i=1;i<n;i++) { while(border>0 && s.charAt(i)!=s.charAt(border)) border=lps[border-1]; if(s.charAt(i)==s.charAt(border)) border=border+1; else border=0; lps[i]=border; } return lps; } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); String s=in.nextLine(); String t=in.nextLine(); int n1=s.length(); int n2=t.length(); int lps[]=kmpsearch(t); int x=0,y=0; for(int i=0;i<n1;i++) { char c=s.charAt(i); if(c=='0') x++; else y++; } StringBuilder sb=new StringBuilder(); int z=0; while(true) { for(int i=z;i<n2;i++) { char c=t.charAt(i); if(c=='0') { if(x>0) { x--; sb.append('0'); } else { for(int ii=1;ii<=y;ii++) sb.append('1'); y=0; } } if(c=='1') { if(y>0) { y--; sb.append('1'); } else { for(int ii=1;ii<=x;ii++) sb.append('0'); x=0; } } } if(x==0&&y==0) break; z=lps[n2-1]; } out.println(sb); 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 ni() { 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 nl() { 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] = ni(); } 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
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
cc99d661c0cff428aa8903a532647cd3
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve(){ s=ns().toCharArray(); t=ns().toCharArray(); computeLPS(); int n=t.length; int c1[]=new int[2]; int c2[]=new int[2]; for(char ch : s) c1[ch-'0']++; for(char ch : t) c2[ch-'0']++; int l=lps[n-1]; if(s.length<t.length || c1[1]<c2[1] || c1[0]<c2[0]){ pw.println(new String(s)); return; } // pw.println(l); pw.print(new String(t)); for(int i=0;i<l;i++) c2[t[i]-'0']--; for(int i=0;i<n;i++) c1[t[i]-'0']--; while(c1[0]>=c2[0] && c1[1]>=c2[1]){ for(int i=l;i<n;i++){ c1[t[i]-'0']--; pw.print(t[i]); } } while(c1[0]-->0) pw.print("0"); while(c1[1]-->0) pw.print("1"); pw.println(""); } char s[],t[]; int lps[]; void computeLPS(){ int n=t.length; lps=new int[n]; for(int i=1;i<n;i++){ int j=lps[i-1]; while(j>0 && t[i]!=t[j]){ j=lps[j-1]; } if(t[i]==t[j]) j++; lps[i]=j; } } long M = (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; 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 (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
d5dad8843199fb16ad806c905ef04b7c
train_000.jsonl
1552035900
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TaskD { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); String t = br.readLine(); int s0 = count(s, '0'); int s1 = count(s, '1'); int t0 = count(t, '0'); int t1 = count(t, '1'); if (t0 > s0 || t1 > s1) { System.out.println(s); } else { int tp = maxPrefixSuffix(t); String tail = t.substring(tp); int tail0 = count(tail, '0'); int tail1 = count(tail, '1'); int l0 = s0; int l1 = s1; StringBuilder result = new StringBuilder(); result.append(t); l0 -= t0; l1 -= t1; while (l0 >= tail0 && l1 >= tail1) { result.append(tail); l0 -= tail0; l1 -= tail1; } while (l0 > 0) { result.append('0'); l0 -= 1; } while (l1 > 0) { result.append('1'); l1 -= 1; } System.out.println(result.toString()); } br.close(); } private static int count(String s, char wantedChar) { return (int) s.chars().filter(ch -> ch == wantedChar).count(); } private static int maxPrefixSuffix(String str) { int[] p = new int[str.length()]; p[0] = 0; for (int i = 1; i < str.length(); i++) { int j = p[i - 1]; while (j > 0 && str.charAt(j) != str.charAt(i)) { j = p[j - 1]; } if (str.charAt(j) == str.charAt(i)) { j++; } p[i] = j; } return p[str.length() - 1]; } }
Java
["101101\n110", "10010110\n100011", "10\n11100"]
1 second
["110110", "01100011", "01"]
NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.
Java 8
standard input
[ "hashing", "string suffix structures", "greedy", "strings" ]
6ac00fcd4a483f9f446e692d05fd31a4
The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.
1,600
In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.
standard output
PASSED
c6e1b830eecb1a9087d514c1dde5cf9b
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner scan=new Scanner(System.in); String s=scan.next(); int[][] memo=new int[26][5001]; int[] sz=new int[26]; for(int i=0;i<26;i++){sz[i]=0;} int n=s.length(); for(int i=0;i<n;i++){ char c=s.charAt(i); int p=c-'a'; memo[p][sz[p]]=i; sz[p]++; } int res=0; for(int i=0;i<26;i++){ int tot=0; for(int d=0;d<=n;d++){ int[] fr=new int[26]; for(int j=0;j<26;j++){fr[j]=0;} for(int k=0;k<sz[i];k++){ int ind=(memo[i][k]+d)%n; int v=s.charAt(ind)-'a'; fr[v]++; } int count=0; for(int j=0;j<26;j++){ if(fr[j]==1){ count++; } } tot=(int)Math.max(tot,count); } res+=tot; } System.out.println(1.0*res/n); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
db67a5550cfdc61527ce65d44c17c40d
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class E931 { public static int mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) { String s=in.nextLine(); int n=s.length(); s=s+s; int[][][] seen=new int[26][n+1][26]; int[][] ones=new int[26][n+1]; for(int i=0;i<n;i++) { int first=s.charAt(i)-'a'; for(int j=0;j<n;j++) { int second=s.charAt(i+j)-'a'; seen[first][j][second]++; if(seen[first][j][second]==1) { ones[first][j]++; } if(seen[first][j][second]==2) { ones[first][j]--; } } } double prob=0; for(int i=0;i<26;i++) { int maxi=0; for(int j=0;j<n;j++) { maxi=max(maxi, ones[i][j]); } prob+=(double)maxi/(double)n; } out.println(prob); out.close(); } public static long pow(long x, long n) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p)) { if ((n & 1) != 0) { res = (res * p); } } return res; } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
2031d6fe378db133dfd946dd9d87c1cf
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jay Leeds */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { StringBuilder s = new StringBuilder(in.nextString()); ArrayList<ArrayList<String>> data = new ArrayList<>(); for (int i = 0; i < 26; i++) data.add(new ArrayList<>()); for (int i = 0; i < s.length(); i++) { data.get(s.charAt(0) - 97).add(s.toString()); char c = s.charAt(0); s = new StringBuilder(s.substring(1)); s.append(c); } double count = 0; for (int i = 0; i < 26; i++) { int[][] used = new int[s.length()][26]; for (String str : data.get(i)) { for (int j = 0; j < s.length(); j++) { used[j][str.charAt(j) - 97]++; } } double best = 0; for (int j = 0; j < used.length; j++) { int num = 0; for (int k = 0; k < 26; k++) if (used[j][k] == 1) num++; best = Math.max(best, (double) num / s.length()); } count += best; } out.printLine(count); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; //Fast IO by Egor Kulikov, modified by myself } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public 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); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void printLine(double i) { writer.println(i); } public void close() { writer.close(); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
c46a45b7f81464892023396beaa87977
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author palayutm */ 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); ProblemEGameWithString solver = new ProblemEGameWithString(); solver.solve(1, in, out); out.close(); } static class ProblemEGameWithString { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.next(); int n = s.length(); ArrayList<Integer>[] arr = new ArrayList[26]; for (int i = 0; i < 26; i++) { arr[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { arr[s.charAt(i) - 'a'].add(i); } int ans = 0; for (int i = 0; i < 26; i++) { int mx = 0; for (int j = 0; j < n; j++) { int[] cnt = new int[26]; for (int p : arr[i]) { cnt[s.charAt((p + j) % n) - 'a']++; } int c = 0; for (int k = 0; k < 26; k++) { if (cnt[k] == 1) c++; } mx = Math.max(mx, c); } ans += mx; } out.printf("%.10f\n", 1.0 * ans / n); } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream out) { super(out); } public OutputWriter(Writer out) { super(out); } public void close() { super.close(); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
8d143ca4fb589db806e615c21d6a5b11
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProblemE { private static class Node{ Node[] c; short childrenCount; Node(){ c = new Node[26]; childrenCount = 0; } } private static class Trie{ Node root; Trie(){ root = new Node(); } } public static void main(String[] args)throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); char[] chars = reader.readLine().toCharArray(); int n = chars.length; int[][][] firstCharLevelCharsCount = new int[26][n + 1][26]; for(int i = 0; i < n; i++){ // possible k int steps = 0; int level = 0; for(int j = i; steps < n; steps++, j = (j + 1) % n){ firstCharLevelCharsCount[chars[i] - 'a'][level][chars[j] - 'a']++; level++; } } int res = 0; for(int i = 0; i < 26; i++){ int count = 0; for(int j = 1; j < n; j++){ int unique = 0; for(int k = 0; k < 26; k++){ if(firstCharLevelCharsCount[i][j][k] == 1){ unique++; } } count = Math.max(count, unique); } res += count; } System.out.println(res/(1.0 * n)); } private static void traverse(Node node, int[][] charLevelCount, int level){ for(int i = 0; i < 26; i++){ if(node.c[i] != null){ charLevelCount[level][i]++; traverse(node.c[i], charLevelCount, level + 1); } } } private static boolean couldBeStart(Node node){ if(node.childrenCount == 1){ for(int i = 0; i < 26; i++){ if(node.c[i] != null){ return couldBeStart(node.c[i]); } } } if(node.childrenCount == 0){ return true; } for(int i = 0; i < 26; i++){ if(node.c[i] != null){ int leafCount = getLeafCount(node.c[i]); if(leafCount > 1){ return false; } } } return true; } private static int getLeafCount(Node node){ if(node.childrenCount == 0){ return 1; } int ret = 0; for(int i = 0; i < 26; i++){ if(node.c[i] != null) { ret += getLeafCount(node.c[i]); } } return ret; } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
f3f62c05c8b052d3b7b72a75e76893c3
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProblemE { public static void main(String[] args)throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); char[] chars = reader.readLine().toCharArray(); int n = chars.length; int[][][] firstCharLevelCharsCount = new int[26][n + 1][26]; for(int i = 0; i < n; i++){ int steps = 0; int level = 0; for(int j = i; steps < n; steps++, j = (j + 1) % n){ firstCharLevelCharsCount[chars[i] - 'a'][level][chars[j] - 'a']++; level++; } } int res = 0; for(int i = 0; i < 26; i++){ int count = 0; for(int j = 1; j < n; j++){ int unique = 0; for(int k = 0; k < 26; k++){ if(firstCharLevelCharsCount[i][j][k] == 1){ unique++; } } count = Math.max(count, unique); } res += count; } System.out.println(res/(1.0 * n)); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
b397d758db7a6ea942bd5f8a65a773cf
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
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 GameWithString { void solve() { char[] s = in.nextToken().toCharArray(); int n = s.length; int[] cnt = new int[26]; for (int i = 0; i < n; i++) cnt[s[i] - 'a']++; int[][] pos = new int[26][]; for (int i = 0; i < 26; i++) pos[i] = new int[cnt[i]]; for (int i = n - 1; i >= 0; i--) pos[s[i] - 'a'][--cnt[s[i] - 'a']] = i; s = Arrays.copyOf(s, n << 1); for (int i = 0; i < n; i++) s[n + i] = s[i]; int ans = 0; for (int c = 0; c < 26; c++) { if (pos[c].length == 0) continue; int best = 0; for (int d = 1; d < n; d++) { int[] test = new int[26]; for (int i : pos[c]) { test[s[i + d] - 'a']++; } int distinct = 0; for (int i = 0; i < 26; i++) { if (test[i] == 1) distinct++; } best = Math.max(best, distinct); } ans += best; } out.println((double) ans / n); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new GameWithString().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
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
2b2622adf8adc0a83a858e8d5e130ce4
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.io.*; import java.text.DecimalFormat; public class E { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); } static class Solver { static long mod = (long) (1e9); public void solve(FastScanner br, PrintWriter pw) throws IOException { String st = br.nt(); String s = st; int L = st.length(); ArrayList<ArrayList<String>> allRotationStartingWith = new ArrayList<ArrayList<String>>(); for (int i = 0; i < 26; i++) allRotationStartingWith.add(new ArrayList<String>()); for (int i = 0; i < L; i++) { allRotationStartingWith.get(s.charAt(0)-97).add(s); s = s.substring(1) + s.charAt(0); } double sumOfAllHighestProbabilities = 0; for (int startingLetterOfRotation = 0; startingLetterOfRotation < 26; startingLetterOfRotation++) { int[][] countsOfLettersSomeDistanceFromStartOfRotation = new int[L][26]; for (String rotation : allRotationStartingWith.get(startingLetterOfRotation)) for (int distanceFromStartOfRotation = 0; distanceFromStartOfRotation < L; distanceFromStartOfRotation++) countsOfLettersSomeDistanceFromStartOfRotation[distanceFromStartOfRotation][rotation.charAt(distanceFromStartOfRotation) - 97]++; double highestProbabilityOfFindingStringShiftWithThisStartingLetterOfRotation = 0; for (int distanceFromStartOfRotation = 0; distanceFromStartOfRotation < L; distanceFromStartOfRotation++) { double counterOfUniqueEndingLetterForSpecificDistanceFromStartOfRotation = 0; for (int endingLetter = 0; endingLetter < 26; endingLetter++) if (countsOfLettersSomeDistanceFromStartOfRotation[distanceFromStartOfRotation][endingLetter] == 1) counterOfUniqueEndingLetterForSpecificDistanceFromStartOfRotation++; highestProbabilityOfFindingStringShiftWithThisStartingLetterOfRotation = Math.max(highestProbabilityOfFindingStringShiftWithThisStartingLetterOfRotation, counterOfUniqueEndingLetterForSpecificDistanceFromStartOfRotation / L); } sumOfAllHighestProbabilities += highestProbabilityOfFindingStringShiftWithThisStartingLetterOfRotation; } pw.println(new DecimalFormat("#0.000000000000000").format(sumOfAllHighestProbabilities)); pw.close(); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
6862a554682f2630e8526f4ecf924330
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; public class CF931_D2_E{ public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); String s=sc.next(); int n=s.length(); ArrayList<String> [] arr=new ArrayList [26]; for(int i=0;i<26;i++) arr[i]=new ArrayList<String>(); for(int i=0;i<n;i++){ s=s.substring(1)+s.charAt(0); arr[s.charAt(0)-'a'].add(s); } double ans=0; for(int i=0;i<26;i++){ int mx=0; for(int j=1;j<n;j++){ boolean [] v=new boolean [26]; boolean [] valid=new boolean [26]; Arrays.fill(valid, true); for(int k=0;k<arr[i].size();k++){ if(v[arr[i].get(k).charAt(j)-'a']) valid[arr[i].get(k).charAt(j)-'a']=false; v[arr[i].get(k).charAt(j)-'a']=true; } int cc=0; for(int ii=0;ii<26;ii++) if(v[ii] && valid[ii]) cc++; mx=Math.max(mx, cc); } ans+=(1.0*mx/n); } pw.println(ans); pw.flush(); pw.close(); } 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
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
16a766d7fd9a01686d9cb192132bfaf5
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.text.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; ArrayList<Integer> al[]; void solve() throws IOException { String s=ns(); int n=s.length(); s=s+s; int count=0; for(int i=0;i<26;i++) { ArrayList<Integer> al=new ArrayList<Integer>(); for(int j=0;j<n;j++) { if(s.charAt(j)-'a'==i) al.add(j); } int max=0; for(int j=1;j<n;j++) { int hash[]=new int[26]; Arrays.fill(hash,-1); int temp=0; for(int k=0;k<al.size();k++) { char ch=s.charAt(al.get(k)+j); if(hash[ch-'a']==-1) hash[ch-'a']=k; else hash[ch-'a']=-2; } for(int k=0;k<26;k++) { if(hash[k]!=-1&&hash[k]!=-2) { temp++; } } max=Math.max(max,temp); } count+=max; } out.println(count*1.0/n); } long ncr[][]; int small[]; void pre(int n) { small=new int[n+1]; for(int i=2;i*i<=n;i++) { for(int j=i;j*i<=n;j++) { if(small[i*j]==0) small[i*j]=i; } } for(int i=0;i<=n;i++) { if(small[i]==0) small[i]=i; } } int sum(int i) { int sum=0; while(i!=0) { if((i%10)%2==1) sum+=i%10; i/=10; } return sum; } /*ArrayList<Integer> al[]; void take(int n,int m) { al=new ArrayList[n]; for(int i=0;i<n;i++) al[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int x=ni()-1; int y=ni()-1; al[x].add(y); al[y].add(x); } }*/ int check(long n) { int count=0; while(n!=0) { if(n%10!=0) break; n/=10; count++; } return count; } public static int count(int x) { int num=0; while(x!=0) { x=x&(x-1); num++; } return num; } static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ int x,y,k; int i,dir; long val; double pos; Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { return Double.compare(this.pos,o.pos); } public String toString(){ return x+" "+y+" "+k+" "+i+" "+val;} public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() ; } } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(y==0) return x; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(y==0) return x; return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code5().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); //new code5().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 long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
17acda17d85b3507f6e453d18ed7b7bb
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { long MOD = 1000000007L; int INF = 1000000000; public class Obj implements Comparable<Obj>{ public int start; public int end; public Obj(int start_, int end_){ this.start = start_; this.end = end_; } public int compareTo(Obj other){ if (other.start == this.start){ return this.end - other.end; } return this.start - other.start; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here Codechef cf = new Codechef(); cf.Solve(); } public void Solve(){ MyScanner sc = new MyScanner(); String s = sc.nextLine(); char[] arr = s.toCharArray(); int len = arr.length; int[] cnt = new int[26]; boolean[] ok = new boolean[26]; int[] pos = new int[len]; int[][] cnt2 = new int[5000][26]; int num = 0; double res = 0.0; for (int i = 0; i < 26; ++i){ char c = (char)(i + 'a'); int sz = 0; for (int j = 0; j < len; ++j){ if (c == arr[j]){ cnt[i]++; pos[sz++] = j; } } if (sz == 0) continue; for (int k = 1; k < len; ++k){ for (int j = 0; j < 26; ++j){ cnt2[k][j] = 0; } } for (int k = 1; k < len; ++k){ for (int j = 0; j < sz; ++j){ int curP = (pos[j] + k) % len; int idx = (int)(arr[curP] - 'a'); cnt2[k][idx]++; } } int best = 0; for (int k = 1; k < len; ++k){ int cur = 0; for (int j = 0; j < sz; ++j){ int curP = (pos[j] + k) % len; int idx = (int)(arr[curP] - 'a'); if (cnt2[k][idx] == 1){ cur++; } } best = Math.max(best, cur); } num += best; } res = 1.0 * num / len; System.out.println(res); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
de710928b77aa0ee983d02bc3cdc0194
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.TreeSet; public final class CF_468_E2 { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} // Global vars static BufferedWriter out; static InputReader reader; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); String s=reader.readString(); int L=s.length(); int CX=26; ArrayList<Integer>[] pos=new ArrayList[CX]; for (int u=0;u<CX;u++) pos[u]=new ArrayList<Integer>(); for (int i=0;i<L;i++) { pos[s.charAt(i)-'a'].add(i); } int bob=0; for (int e=0;e<CX;e++){ int[][] used=new int[L][CX]; for (int i:pos[e]){ for (int u=0;u<L;u++){ int y=s.charAt((i+u)%L)-'a'; used[u][y]++; } } int mx=0; int tgt=-1; for (int i=0;i<L;i++){ int disc=0; for (int x:pos[e]){ int y=s.charAt((i+x)%L)-'a'; if (used[i][y]==1) disc++; } if (disc>mx){ mx=disc; tgt=i; } } bob+=mx; } double prob=bob; prob/=L; output(prob); try { out.close(); } catch (Exception EX){} } static void processKO() throws Exception { //log(0.75*4+3+3); out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); String s=reader.readString(); int L=s.length(); int CX=26; int[] cnt=new int[CX]; for (int i=0;i<L;i++) cnt[s.charAt(i)-'a']++; char[] mem=new char[2*L]; for (int u=0;u<2*L;u++) mem[u]=s.charAt(u%L); ArrayList<String>[] hs=new ArrayList[CX]; int[][][] used=new int[CX][L][CX]; int[] num=new int[CX]; for (int i=0;i<L;i++){ // pick shifted // look at begining // see if we can differentiate // start at i int x=mem[i]-'a'; num[x]++; char[] tmp=new char[L]; for (int u=0;u<L;u++){ int y=mem[i+u]-'a'; tmp[u]=mem[i+u]; used[x][u][y]=1; } log(new String(tmp)); } double prob=0; for (int u=0;u<CX;u++){ if (num[u]>0){ //log((char)(u+'a')+" "+num[u]); boolean found=false; int mdiff=0; lp:for (int i=0;i<L;i++){ int diff=0; for (int v=0;v<CX;v++){ if (used[u][i][v]==1) diff++; } mdiff=Math.max(diff,mdiff); if (diff==num[u]){ found=true; break lp; } } log("u:"+(char)(u+'a')+" found "+num[u]+" occurences and was able to separate "+mdiff); //double freq=num[u]; //freq/=L; double freq=num[u]; freq/=L; if (mdiff==num[u]) prob+=freq; } } /* double res=win; res/=(win+lose); double min=1; min/=L; res=Math.max(res,min); output(res); */ output(prob); try { out.close(); } catch (Exception EX){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
c1f966d775ba043e0c84bcc791f5e9ee
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.TreeSet; public final class CF_468_E { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} // Global vars static BufferedWriter out; static InputReader reader; static void process() throws Exception { //log(0.75*4+3+3); out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); String s=reader.readString(); int L=s.length(); int CX=26; ArrayList<Integer>[] pos=new ArrayList[CX]; for (int u=0;u<CX;u++) pos[u]=new ArrayList<Integer>(); for (int i=0;i<L;i++) { pos[s.charAt(i)-'a'].add(i); } char[] mem=new char[2*L]; for (int u=0;u<2*L;u++) mem[u]=s.charAt(u%L); ArrayList<String>[] hs=new ArrayList[CX]; int[][][] used=new int[CX][L][CX]; int[] num=new int[CX]; //String[] stmp=new String[L]; for (int i=0;i<L;i++){ // pick shifted // look at begining // see if we can differentiate // start at i int x=mem[i]-'a'; num[x]++; //char[] tmp=new char[L]; for (int u=0;u<L;u++){ int y=mem[i+u]-'a'; //tmp[u]=mem[i+u]; used[x][u][y]++; } //stmp[i]=new String(tmp); //log(stmp[i]); } double prob=0; double base=1.0/L; // redo the algo // must pick position // and see how many are distingued with this // THIS IS BUGGED.... int bob=0; for (int u=0;u<CX;u++){ int mx=0; int tgt=-1; for (int i=0;i<L;i++){ int disc=0; for (int x:pos[u]){ int y=mem[i+x]-'a'; if (used[u][i][y]==1) disc++; } if (disc>mx){ mx=disc; tgt=i; } } //log("u:"+(char)(u+'a')+" mx:"+mx+" @pos:"+tgt); bob+=mx; } prob=bob; prob/=L; output(prob); try { out.close(); } catch (Exception EX){} } static void processKO() throws Exception { //log(0.75*4+3+3); out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); String s=reader.readString(); int L=s.length(); int CX=26; int[] cnt=new int[CX]; for (int i=0;i<L;i++) cnt[s.charAt(i)-'a']++; char[] mem=new char[2*L]; for (int u=0;u<2*L;u++) mem[u]=s.charAt(u%L); ArrayList<String>[] hs=new ArrayList[CX]; int[][][] used=new int[CX][L][CX]; int[] num=new int[CX]; for (int i=0;i<L;i++){ // pick shifted // look at begining // see if we can differentiate // start at i int x=mem[i]-'a'; num[x]++; char[] tmp=new char[L]; for (int u=0;u<L;u++){ int y=mem[i+u]-'a'; tmp[u]=mem[i+u]; used[x][u][y]=1; } log(new String(tmp)); } double prob=0; for (int u=0;u<CX;u++){ if (num[u]>0){ //log((char)(u+'a')+" "+num[u]); boolean found=false; int mdiff=0; lp:for (int i=0;i<L;i++){ int diff=0; for (int v=0;v<CX;v++){ if (used[u][i][v]==1) diff++; } mdiff=Math.max(diff,mdiff); if (diff==num[u]){ found=true; break lp; } } log("u:"+(char)(u+'a')+" found "+num[u]+" occurences and was able to separate "+mdiff); //double freq=num[u]; //freq/=L; double freq=num[u]; freq/=L; if (mdiff==num[u]) prob+=freq; } } /* double res=win; res/=(win+lose); double min=1; min/=L; res=Math.max(res,min); output(res); */ output(prob); try { out.close(); } catch (Exception EX){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
363aef71cac0ebb95b8ef9ed1f98b69a
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; public class E_468 { public static final long[] POWER2 = generatePOWER2(); public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator()); public static long BIG = 1000000000 + 7; private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer stringTokenizer = null; private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class Array<Type> implements Iterable<Type> { private final Object[] array; public Array(int size) { this.array = new Object[size]; } public Array(int size, Type element) { this(size); Arrays.fill(this.array, element); } public Array(Array<Type> array, Type element) { this(array.size() + 1); for (int index = 0; index < array.size(); index++) { set(index, array.get(index)); } set(size() - 1, element); } public Array(List<Type> list) { this(list.size()); int index = 0; for (Type element : list) { set(index, element); index += 1; } } public Type get(int index) { return (Type) this.array[index]; } @Override public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < size(); } @Override public Type next() { Type result = Array.this.get(index); index += 1; return result; } }; } public Array set(int index, Type value) { this.array[index] = value; return this; } public int size() { return this.array.length; } public List<Type> toList() { List<Type> result = new ArrayList<>(); for (Type element : this) { result.add(element); } return result; } @Override public String toString() { return "[" + E_468.toString(this, ", ") + "]"; } } static class BIT { private static int lastBit(int index) { return index & -index; } private final long[] tree; public BIT(int size) { this.tree = new long[size]; } public void add(int index, long delta) { index += 1; while (index <= this.tree.length) { tree[index - 1] += delta; index += lastBit(index); } } public long prefix(int end) { long result = 0; while (end > 0) { result += this.tree[end - 1]; end -= lastBit(end); } return result; } public int size() { return this.tree.length; } public long sum(int start, int end) { return prefix(end) - prefix(start); } } static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> { public final TypeVertex vertex0; public final TypeVertex vertex1; public final boolean bidirectional; public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { this.vertex0 = vertex0; this.vertex1 = vertex1; this.bidirectional = bidirectional; this.vertex0.edges.add(getThis()); if (this.bidirectional) { this.vertex1.edges.add(getThis()); } } public abstract TypeEdge getThis(); public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex) { TypeVertex result; if (vertex0 == vertex) { result = vertex1; } else { result = vertex0; } return result; } public void remove() { this.vertex0.edges.remove(getThis()); if (this.bidirectional) { this.vertex1.edges.remove(getThis()); } } @Override public String toString() { return this.vertex0 + "->" + this.vertex1; } } public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>> { public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefault<TypeVertex> getThis() { return this; } } public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault> { public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefaultDefault getThis() { return this; } } public static class FIFO<Type> { public SingleLinkedList<Type> start; public SingleLinkedList<Type> end; public FIFO() { this.start = null; this.end = null; } public boolean isEmpty() { return this.start == null; } public Type peek() { return this.start.element; } public Type pop() { Type result = this.start.element; this.start = this.start.next; return result; } public void push(Type element) { SingleLinkedList<Type> list = new SingleLinkedList<>(element, null); if (this.start == null) { this.start = list; this.end = list; } else { this.end.next = list; this.end = list; } } } static class Fraction implements Comparable<Fraction> { public static final Fraction ZERO = new Fraction(0, 1); public static Fraction fraction(long whole) { return fraction(whole, 1); } public static Fraction fraction(long numerator, long denominator) { Fraction result; if (denominator == 0) { throw new ArithmeticException(); } if (numerator == 0) { result = Fraction.ZERO; } else { int sign; if (numerator < 0 ^ denominator < 0) { sign = -1; numerator = Math.abs(numerator); denominator = Math.abs(denominator); } else { sign = 1; } long gcd = gcd(numerator, denominator); result = new Fraction(sign * numerator / gcd, denominator / gcd); } return result; } public final long numerator; public final long denominator; private Fraction(long numerator, long denominator) { this.numerator = numerator; this.denominator = denominator; } public Fraction add(Fraction fraction) { return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator); } @Override public int compareTo(Fraction that) { return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator); } public Fraction divide(Fraction fraction) { return multiply(fraction.inverse()); } public boolean equals(Fraction that) { return this.compareTo(that) == 0; } public boolean equals(Object that) { return this.compareTo((Fraction) that) == 0; } public Fraction getRemainder() { return fraction(this.numerator - getWholePart() * denominator, denominator); } public long getWholePart() { return this.numerator / this.denominator; } public Fraction inverse() { return fraction(this.denominator, this.numerator); } public Fraction multiply(Fraction fraction) { return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator); } public Fraction neg() { return fraction(-this.numerator, this.denominator); } public Fraction sub(Fraction fraction) { return add(fraction.neg()); } @Override public String toString() { String result; if (getRemainder().equals(Fraction.ZERO)) { result = "" + this.numerator; } else { result = this.numerator + "/" + this.denominator; } return result; } } static class IteratorBuffer<Type> { private Iterator<Type> iterator; private List<Type> list; public IteratorBuffer(Iterator<Type> iterator) { this.iterator = iterator; this.list = new ArrayList<Type>(); } public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < list.size() || IteratorBuffer.this.iterator.hasNext(); } @Override public Type next() { if (list.size() <= this.index) { list.add(iterator.next()); } Type result = list.get(index); index += 1; return result; } }; } } public static class MapCount<Type> extends SortedMapAVL<Type, Long> { private int count; public MapCount(Comparator<? super Type> comparator) { super(comparator); this.count = 0; } public long add(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key); if (value == null) { value = delta; } else { value += delta; } put(key, value); result = delta; } else { result = 0; } this.count += result; return result; } public int count() { return this.count; } public List<Type> flatten() { List<Type> result = new ArrayList<>(); for (Entry<Type, Long> entry : entrySet()) { for (long index = 0; index < entry.getValue(); index++) { result.add(entry.getKey()); } } return result; } @Override public SortedMapAVL<Type, Long> headMap(Type keyEnd) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends Type, ? extends Long> map) { throw new UnsupportedOperationException(); } public long remove(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key) - delta; if (value <= 0) { result = delta + value; remove(key); } else { result = delta; put(key, value); } } else { result = 0; } this.count -= result; return result; } @Override public Long remove(Object key) { Long result = super.remove(key); this.count -= result; return result; } @Override public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd) { throw new UnsupportedOperationException(); } @Override public SortedMapAVL<Type, Long> tailMap(Type keyStart) { throw new UnsupportedOperationException(); } } public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue> { private Comparator<? super TypeValue> comparatorValue; public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey); this.comparatorValue = comparatorValue; } public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey, entrySet); this.comparatorValue = comparatorValue; } public boolean add(TypeKey key, TypeValue value) { SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue)); return set.add(value); } public TypeValue firstValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry(); if (firstEntry == null) { result = null; } else { result = firstEntry.getValue().first(); } return result; } @Override public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue); } public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator(); Iterator<TypeValue> iteratorValue = null; @Override public boolean hasNext() { return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext()); } @Override public TypeValue next() { if (iteratorValue == null || !iteratorValue.hasNext()) { iteratorValue = iteratorValues.next().iterator(); } return iteratorValue.next(); } }; } public TypeValue lastValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry(); if (lastEntry == null) { result = null; } else { result = lastEntry.getValue().last(); } return result; } public boolean removeSet(TypeKey key, TypeValue value) { boolean result; SortedSetAVL<TypeValue> set = get(key); if (set == null) { result = false; } else { result = set.remove(value); if (set.size() == 0) { remove(key); } } return result; } @Override public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue); } } public static class Matrix { public final int rows; public final int columns; public final Fraction[][] cells; public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.cells = new Fraction[rows][columns]; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { set(row, column, Fraction.ZERO); } } } public void add(int rowSource, int rowTarget, Fraction fraction) { for (int column = 0; column < columns; column++) { this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction)); } } private int columnPivot(int row) { int result = this.columns; for (int column = this.columns - 1; 0 <= column; column--) { if (this.cells[row][column].compareTo(Fraction.ZERO) != 0) { result = column; } } return result; } public void reduce() { for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++) { int rowPivot = rowPivot(rowMinimum); if (rowPivot != -1) { int columnPivot = columnPivot(rowPivot); Fraction current = this.cells[rowMinimum][columnPivot]; Fraction pivot = this.cells[rowPivot][columnPivot]; Fraction fraction = pivot.inverse().sub(current.divide(pivot)); add(rowPivot, rowMinimum, fraction); for (int row = rowMinimum + 1; row < this.rows; row++) { if (columnPivot(row) == columnPivot) { add(rowMinimum, row, this.cells[row][columnPivot(row)].neg()); } } } } } private int rowPivot(int rowMinimum) { int result = -1; int pivotColumnMinimum = this.columns; for (int row = rowMinimum; row < this.rows; row++) { int pivotColumn = columnPivot(row); if (pivotColumn < pivotColumnMinimum) { result = row; pivotColumnMinimum = pivotColumn; } } return result; } public void set(int row, int column, Fraction value) { this.cells[row][column] = value; } public String toString() { String result = ""; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { result += this.cells[row][column] + "\t"; } result += "\n"; } return result; } } public static class Node<Type> { public static <Type> Node<Type> balance(Node<Type> result) { while (result != null && 1 < Math.abs(height(result.left) - height(result.right))) { if (height(result.left) < height(result.right)) { Node<Type> right = result.right; if (height(right.right) < height(right.left)) { result = new Node<>(result.value, result.left, right.rotateRight()); } result = result.rotateLeft(); } else { Node<Type> left = result.left; if (height(left.left) < height(left.right)) { result = new Node<>(result.value, left.rotateLeft(), result.right); } result = result.rotateRight(); } } return result; } public static <Type> Node<Type> clone(Node<Type> result) { if (result != null) { result = new Node<>(result.value, clone(result.left), clone(result.right)); } return result; } public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { if (node.left == null) { result = node.right; } else { if (node.right == null) { result = node.left; } else { Node<Type> first = first(node.right); result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator)); } } } else { if (compare < 0) { result = new Node<>(node.value, delete(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, delete(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> first(Node<Type> result) { while (result.left != null) { result = result.left; } return result; } public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node; } else { if (compare < 0) { result = get(node.left, value, comparator); } else { result = get(node.right, value, comparator); } } } return result; } public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node.left; } else { if (compare < 0) { result = head(node.left, value, comparator); } else { result = new Node<>(node.value, node.left, head(node.right, value, comparator)); } } result = balance(result); } return result; } public static int height(Node node) { return node == null ? 0 : node.height; } public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = new Node<>(value, null, null); } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(value, node.left, node.right); ; } else { if (compare < 0) { result = new Node<>(node.value, insert(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, insert(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> last(Node<Type> result) { while (result.right != null) { result = result.right; } return result; } public static int size(Node node) { return node == null ? 0 : node.size; } public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(node.value, null, node.right); } else { if (compare < 0) { result = new Node<>(node.value, tail(node.left, value, comparator), node.right); } else { result = tail(node.right, value, comparator); } } result = balance(result); } return result; } public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer) { if (node != null) { traverseOrderIn(node.left, consumer); consumer.accept(node.value); traverseOrderIn(node.right, consumer); } } public final Type value; public final Node<Type> left; public final Node<Type> right; public final int size; private final int height; public Node(Type value, Node<Type> left, Node<Type> right) { this.value = value; this.left = left; this.right = right; this.size = 1 + size(left) + size(right); this.height = 1 + Math.max(height(left), height(right)); } public Node<Type> rotateLeft() { Node<Type> left = new Node<>(this.value, this.left, this.right.left); return new Node<>(this.right.value, left, this.right.right); } public Node<Type> rotateRight() { Node<Type> right = new Node<>(this.value, this.left.right, this.right); return new Node<>(this.left.value, this.left.left, right); } } public static class SingleLinkedList<Type> { public final Type element; public SingleLinkedList<Type> next; public SingleLinkedList(Type element, SingleLinkedList<Type> next) { this.element = element; this.next = next; } public void toCollection(Collection<Type> collection) { if (this.next != null) { this.next.toCollection(collection); } collection.add(this.element); } } public static class SmallSetIntegers { public static final int SIZE = 20; public static final int[] SET = generateSet(); public static final int[] COUNT = generateCount(); public static final int[] INTEGER = generateInteger(); private static int count(int set) { int result = 0; for (int integer = 0; integer < SIZE; integer++) { if (0 < (set & set(integer))) { result += 1; } } return result; } private static final int[] generateCount() { int[] result = new int[1 << SIZE]; for (int set = 0; set < result.length; set++) { result[set] = count(set); } return result; } private static final int[] generateInteger() { int[] result = new int[1 << SIZE]; Arrays.fill(result, -1); for (int integer = 0; integer < SIZE; integer++) { result[SET[integer]] = integer; } return result; } private static final int[] generateSet() { int[] result = new int[SIZE]; for (int integer = 0; integer < result.length; integer++) { result[integer] = set(integer); } return result; } private static int set(int integer) { return 1 << integer; } } public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue> { public final Comparator<? super TypeKey> comparator; public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet; public SortedMapAVL(Comparator<? super TypeKey> comparator) { this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey()))); } private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet) { this.comparator = comparator; this.entrySet = entrySet; } @Override public void clear() { this.entrySet.clear(); } @Override public Comparator<? super TypeKey> comparator() { return this.comparator; } @Override public boolean containsKey(Object key) { return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null)); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet() { return this.entrySet; } public Entry<TypeKey, TypeValue> firstEntry() { return this.entrySet.first(); } @Override public TypeKey firstKey() { return firstEntry().getKey(); } @Override public TypeValue get(Object key) { Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); entry = this.entrySet.get(entry); return entry == null ? null : entry.getValue(); } @Override public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public boolean isEmpty() { return this.entrySet.isEmpty(); } @Override public Set<TypeKey> keySet() { return new SortedSet<TypeKey>() { @Override public boolean add(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeKey> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Comparator<? super TypeKey> comparator() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public TypeKey first() { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> headSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public Iterator<TypeKey> iterator() { final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); return new Iterator<TypeKey>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public TypeKey next() { return iterator.next().getKey(); } }; } @Override public TypeKey last() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1) { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> tailSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } public Entry<TypeKey, TypeValue> lastEntry() { return this.entrySet.last(); } @Override public TypeKey lastKey() { return lastEntry().getKey(); } @Override public TypeValue put(TypeKey key, TypeValue value) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value); this.entrySet().add(entry); return result; } @Override public void putAll(Map<? extends TypeKey, ? extends TypeValue> map) { map.entrySet() .forEach(entry -> put(entry.getKey(), entry.getValue())); } @Override public TypeValue remove(Object key) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); this.entrySet.remove(entry); return result; } @Override public int size() { return this.entrySet().size(); } @Override public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null))); } @Override public String toString() { return this.entrySet().toString(); } @Override public Collection<TypeValue> values() { return new Collection<TypeValue>() { @Override public boolean add(TypeValue typeValue) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeValue> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object value) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return SortedMapAVL.this.entrySet.isEmpty(); } @Override public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public TypeValue next() { return this.iterator.next().getValue(); } }; } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } } public static class SortedSetAVL<Type> implements SortedSet<Type> { public Comparator<? super Type> comparator; public Node<Type> root; private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root) { this.comparator = comparator; this.root = root; } public SortedSetAVL(Comparator<? super Type> comparator) { this(comparator, null); } public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator) { this(comparator, null); this.addAll(collection); } public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL) { this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root)); } @Override public boolean add(Type value) { int sizeBefore = size(); this.root = Node.insert(this.root, value, this.comparator); return sizeBefore != size(); } @Override public boolean addAll(Collection<? extends Type> collection) { return collection.stream() .map(this::add) .reduce(true, (x, y) -> x | y); } @Override public void clear() { this.root = null; } @Override public Comparator<? super Type> comparator() { return this.comparator; } @Override public boolean contains(Object value) { return Node.get(this.root, (Type) value, this.comparator) != null; } @Override public boolean containsAll(Collection<?> collection) { return collection.stream() .allMatch(this::contains); } @Override public Type first() { return Node.first(this.root).value; } public Type get(Type value) { Node<Type> node = Node.get(this.root, value, this.comparator); return node == null ? null : node.value; } @Override public SortedSetAVL<Type> headSet(Type valueEnd) { return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator)); } @Override public boolean isEmpty() { return this.root == null; } @Override public Iterator<Type> iterator() { Stack<Node<Type>> path = new Stack<>(); return new Iterator<Type>() { { push(SortedSetAVL.this.root); } @Override public boolean hasNext() { return !path.isEmpty(); } @Override public Type next() { if (path.isEmpty()) { throw new NoSuchElementException(); } else { Node<Type> node = path.peek(); Type result = node.value; if (node.right != null) { push(node.right); } else { do { node = path.pop(); } while (!path.isEmpty() && path.peek().right == node); } return result; } } public void push(Node<Type> node) { while (node != null) { path.push(node); node = node.left; } } }; } @Override public Type last() { return Node.last(this.root).value; } @Override public boolean remove(Object value) { int sizeBefore = size(); this.root = Node.delete(this.root, (Type) value, this.comparator); return sizeBefore != size(); } @Override public boolean removeAll(Collection<?> collection) { return collection.stream() .map(this::remove) .reduce(true, (x, y) -> x | y); } @Override public boolean retainAll(Collection<?> collection) { SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator); collection.stream() .map(element -> (Type) element) .filter(this::contains) .forEach(set::add); boolean result = size() != set.size(); this.root = set.root; return result; } @Override public int size() { return this.root == null ? 0 : this.root.size; } @Override public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd) { return tailSet(valueStart).headSet(valueEnd); } @Override public SortedSetAVL<Type> tailSet(Type valueStart) { return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator)); } @Override public Object[] toArray() { return toArray(new Object[0]); } @Override public <T> T[] toArray(T[] ts) { List<Object> list = new ArrayList<>(); Node.traverseOrderIn(this.root, list::add); return list.toArray(ts); } @Override public String toString() { return "{" + E_468.toString(this, ", ") + "}"; } } public static class Tree2D { public static final int SIZE = 1 << 30; public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null }; public static boolean contains(int x, int y, int left, int bottom, int size) { return left <= x && x < left + size && bottom <= y && y < bottom + size; } public static int count(Tree2D[] trees) { int result = 0; for (int index = 0; index < 4; index++) { if (trees[index] != null) { result += trees[index].count; } } return result; } public static int count ( int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop, Tree2D tree, int left, int bottom, int size ) { int result; if (tree == null) { result = 0; } else { int right = left + size; int top = bottom + size; int intersectionLeft = Math.max(rectangleLeft, left); int intersectionBottom = Math.max(rectangleBottom, bottom); int intersectionRight = Math.min(rectangleRight, right); int intersectionTop = Math.min(rectangleTop, top); if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom) { result = 0; } else { if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top) { result = tree.count; } else { size = size >> 1; result = 0; for (int index = 0; index < 4; index++) { result += count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } } } } return result; } public static int quadrantBottom(int bottom, int size, int index) { return bottom + (index >> 1) * size; } public static int quadrantLeft(int left, int size, int index) { return left + (index & 1) * size; } public final Tree2D[] trees; public final int count; private Tree2D(Tree2D[] trees, int count) { this.trees = trees; this.count = count; } public Tree2D(Tree2D[] trees) { this(trees, count(trees)); } public Tree2D() { this(TREES_NULL); } public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop) { return count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, this, 0, 0, SIZE ); } public Tree2D setPoint ( int x, int y, Tree2D tree, int left, int bottom, int size ) { Tree2D result; if (contains(x, y, left, bottom, size)) { if (size == 1) { result = new Tree2D(TREES_NULL, 1); } else { size = size >> 1; Tree2D[] trees = new Tree2D[4]; for (int index = 0; index < 4; index++) { trees[index] = setPoint ( x, y, tree == null ? null : tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } result = new Tree2D(trees); } } else { result = tree; } return result; } public Tree2D setPoint(int x, int y) { return setPoint ( x, y, this, 0, 0, SIZE ); } } public static class Tuple2<Type0, Type1> { public final Type0 v0; public final Type1 v1; public Tuple2(Type0 v0, Type1 v1) { this.v0 = v0; this.v1 = v1; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ")"; } } public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>> { public Tuple2Comparable(Type0 v0, Type1 v1) { super(v0, v1); } @Override public int compareTo(Tuple2Comparable<Type0, Type1> that) { int result = this.v0.compareTo(that.v0); if (result == 0) { result = this.v1.compareTo(that.v1); } return result; } } public static class Tuple3<Type0, Type1, Type2> { public final Type0 v0; public final Type1 v1; public final Type2 v2; public Tuple3(Type0 v0, Type1 v1, Type2 v2) { this.v0 = v0; this.v1 = v1; this.v2 = v2; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")"; } } public static class Vertex < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>> { public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( TypeVertex vertex, TypeEdge edge, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, Array<Boolean> visited, FIFO<TypeVertex> verticesNext, FIFO<TypeEdge> edgesNext, TypeResult result ) { if (!visited.get(vertex.index)) { visited.set(vertex.index, true); result = function.apply(vertex, edge, result); for (TypeEdge edgeNext : vertex.edges) { TypeVertex vertexNext = edgeNext.other(vertex); if (!visited.get(vertexNext.index)) { verticesNext.push(vertexNext); edgesNext.push(edgeNext); } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( Array<TypeVertex> vertices, int indexVertexStart, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, TypeResult result ) { Array<Boolean> visited = new Array<>(vertices.size(), false); FIFO<TypeVertex> verticesNext = new FIFO<>(); verticesNext.push(vertices.get(indexVertexStart)); FIFO<TypeEdge> edgesNext = new FIFO<>(); edgesNext.push(null); while (!verticesNext.isEmpty()) { result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result); } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > boolean cycle ( TypeVertex start, SortedSet<TypeVertex> result ) { boolean cycle = false; Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (!result.contains(vertex)) { result.add(vertex); for (TypeEdge otherEdge : vertex.edges) { if (otherEdge != edge) { TypeVertex otherVertex = otherEdge.other(vertex); if (result.contains(otherVertex)) { cycle = true; } else { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } } return cycle; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, BiConsumer<TypeVertex, TypeEdge> functionVisitPre, BiConsumer<TypeVertex, TypeEdge> functionVisitPost ) { SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder()); Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (result.contains(vertex)) { functionVisitPost.accept(vertex, edge); } else { result.add(vertex); stackVertex.push(vertex); stackEdge.push(edge); functionVisitPre.accept(vertex, edge); for (TypeEdge otherEdge : vertex.edges) { TypeVertex otherVertex = otherEdge.other(vertex); if (!result.contains(otherVertex)) { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, Consumer<TypeVertex> functionVisitPreVertex, Consumer<TypeVertex> functionVisitPostVertex ) { BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) -> { functionVisitPreVertex.accept(vertex); }; BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) -> { functionVisitPostVertex.accept(vertex); }; return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge); } public final int index; public final List<TypeEdge> edges; public Vertex(int index) { this.index = index; this.edges = new ArrayList<>(); } @Override public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that) { return Integer.compare(this.index, that.index); } @Override public String toString() { return "" + this.index; } } public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge> { public VertexDefault(int index) { super(index); } } public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault> { public static Array<VertexDefaultDefault> vertices(int n) { Array<VertexDefaultDefault> result = new Array<>(n); for (int index = 0; index < n; index++) { result.set(index, new VertexDefaultDefault(index)); } return result; } public VertexDefaultDefault(int index) { super(index); } } public static class Wrapper<Type> { public Type value; public Wrapper(Type value) { this.value = value; } public Type get() { return this.value; } public void set(Type value) { this.value = value; } @Override public String toString() { return this.value.toString(); } } public static void add(int delta, int[] result) { for (int index = 0; index < result.length; index++) { result[index] += delta; } } public static void add(int delta, int[]... result) { for (int index = 0; index < result.length; index++) { add(delta, result[index]); } } public static long add(long x, long y) { return (x + y) % BIG; } public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end) { return -binarySearchMinimum(x -> filter.apply(-x), -end, -start); } public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end) { int result; if (start == end) { result = end; } else { int middle = start + (end - start) / 2; if (filter.apply(middle)) { result = binarySearchMinimum(filter, start, middle); } else { result = binarySearchMinimum(filter, middle + 1, end); } } return result; } public static void close() { out.close(); } private static void combinations(int n, int k, int start, SortedSet<Integer> combination, List<SortedSet<Integer>> result) { if (k == 0) { result.add(new SortedSetAVL<>(combination, Comparator.naturalOrder())); } else { for (int index = start; index < n; index++) { if (!combination.contains(index)) { combination.add(index); combinations(n, k - 1, index + 1, combination, result); combination.remove(index); } } } } public static List<SortedSet<Integer>> combinations(int n, int k) { List<SortedSet<Integer>> result = new ArrayList<>(); combinations(n, k, 0, new SortedSetAVL<>(Comparator.naturalOrder()), result); return result; } public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator) { int result = 0; while (result == 0 && iterator0.hasNext() && iterator1.hasNext()) { result = comparator.compare(iterator0.next(), iterator1.next()); } if (result == 0) { if (iterator1.hasNext()) { result = -1; } else { if (iterator0.hasNext()) { result = 1; } } } return result; } public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator) { return compare(iterable0.iterator(), iterable1.iterator(), comparator); } public static long divideCeil(long x, long y) { return (x + y - 1) / y; } public static Set<Long> divisors(long n) { SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder()); result.add(1L); for (Long factor : factors(n)) { SortedSetAVL<Long> divisors = new SortedSetAVL<>(result); for (Long divisor : result) { divisors.add(divisor * factor); } result = divisors; } return result; } public static LinkedList<Long> factors(long n) { LinkedList<Long> result = new LinkedList<>(); Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while (n > 1 && (prime = primes.next()) * prime <= n) { while (n % prime == 0) { result.add(prime); n /= prime; } } if (n > 1) { result.add(n); } return result; } public static long faculty(int n) { long result = 1; for (int index = 2; index <= n; index++) { result *= index; } return result; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public static long[] generatePOWER2() { long[] result = new long[63]; for (int x = 0; x < result.length; x++) { result[x] = 1L << x; } return result; } public static boolean isPrime(long x) { boolean result = x > 1; Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while ((prime = iterator.next()) * prime <= x) { result &= x % prime > 0; } return result; } public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum) { long[] valuesMaximum = new long[weightMaximum + 1]; for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount) { long itemValue = itemValueWeightCount.v0; int itemWeight = itemValueWeightCount.v1; int itemCount = itemValueWeightCount.v2; for (int weight = weightMaximum; 0 <= weight; weight--) { for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++) { valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue); } } } long result = 0; for (long valueMaximum : valuesMaximum) { result = Math.max(result, valueMaximum); } return result; } public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum) { boolean[] weightPossible = new boolean[weightMaximum + 1]; weightPossible[0] = true; int weightLargest = 0; for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount) { int itemWeight = itemWeightCount.v0; int itemCount = itemWeightCount.v1; for (int weightStart = 0; weightStart < itemWeight; weightStart++) { int count = 0; for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight) { if (weightPossible[weight]) { count = itemCount; } else { if (0 < count) { weightPossible[weight] = true; weightLargest = weight; count -= 1; } } } } } return weightPossible[weightMaximum]; } public static long lcm(int a, int b) { return a * b / gcd(a, b); } public static void main(String[] args) { try { solve(); } catch (IOException exception) { exception.printStackTrace(); } close(); } public static long mul(long x, long y) { return (x * y) % BIG; } public static double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public static int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static void nextInts(int n, int[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextInt(); } } } public static int[] nextInts(int n) throws IOException { int[] result = new int[n]; nextInts(n, result); return result; } public static String nextLine() throws IOException { return bufferedReader.readLine(); } public static long nextLong() throws IOException { return Long.parseLong(nextString()); } public static void nextLongs(int n, long[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextLong(); } } } public static long[] nextLongs(int n) throws IOException { long[] result = new long[n]; nextLongs(n, result); return result; } public static String nextString() throws IOException { while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens())) { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } return stringTokenizer.nextToken(); } public static String[] nextStrings(int n) throws IOException { String[] result = new String[n]; { for (int index = 0; index < n; index++) { result[index] = nextString(); } } return result; } public static <T> List<T> permutation(long p, List<T> x) { List<T> copy = new ArrayList<>(); for (int index = 0; index < x.size(); index++) { copy.add(x.get(index)); } List<T> result = new ArrayList<>(); for (int indexTo = 0; indexTo < x.size(); indexTo++) { int indexFrom = (int) p % copy.size(); p = p / copy.size(); result.add(copy.remove(indexFrom)); } return result; } public static <Type> List<List<Type>> permutations(List<Type> list) { List<List<Type>> result = new ArrayList<>(); result.add(new ArrayList<>()); for (Type element : list) { List<List<Type>> permutations = result; result = new ArrayList<>(); for (List<Type> permutation : permutations) { for (int index = 0; index <= permutation.size(); index++) { List<Type> permutationNew = new ArrayList<>(permutation); permutationNew.add(index, element); result.add(permutationNew); } } } return result; } public static long[][] sizeGroup2CombinationsCount(int maximum) { long[][] result = new long[maximum + 1][maximum + 1]; for (int length = 0; length <= maximum; length++) { result[length][0] = 1; for (int group = 1; group <= length; group++) { result[length][group] = add(result[length - 1][group - 1], result[length - 1][group]); } } return result; } public static Stream<BigInteger> streamFibonacci() { return Stream.generate(new Supplier<BigInteger>() { private BigInteger n0 = BigInteger.ZERO; private BigInteger n1 = BigInteger.ONE; @Override public BigInteger get() { BigInteger result = n0; n0 = n1; n1 = result.add(n0); return result; } }); } public static Stream<Long> streamPrime(int sieveSize) { return Stream.generate(new Supplier<Long>() { private boolean[] isPrime = new boolean[sieveSize]; private long sieveOffset = 2; private List<Long> primes = new ArrayList<>(); private int index = 0; public void filter(long prime, boolean[] result) { if (prime * prime < this.sieveOffset + sieveSize) { long remainingStart = this.sieveOffset % prime; long start = remainingStart == 0 ? 0 : prime - remainingStart; for (long index = start; index < sieveSize; index += prime) { result[(int) index] = false; } } } public void generatePrimes() { Arrays.fill(this.isPrime, true); this.primes.forEach(prime -> filter(prime, isPrime)); for (int index = 0; index < sieveSize; index++) { if (isPrime[index]) { this.primes.add(this.sieveOffset + index); filter(this.sieveOffset + index, isPrime); } } this.sieveOffset += sieveSize; } @Override public Long get() { while (this.primes.size() <= this.index) { generatePrimes(); } Long result = this.primes.get(this.index); this.index += 1; return result; } }); } public static <Type> String toString(Iterator<Type> iterator, String separator) { StringBuilder stringBuilder = new StringBuilder(); if (iterator.hasNext()) { stringBuilder.append(iterator.next()); } while (iterator.hasNext()) { stringBuilder.append(separator); stringBuilder.append(iterator.next()); } return stringBuilder.toString(); } public static <Type> String toString(Iterator<Type> iterator) { return toString(iterator, " "); } public static <Type> String toString(Iterable<Type> iterable, String separator) { return toString(iterable.iterator(), separator); } public static <Type> String toString(Iterable<Type> iterable) { return toString(iterable, " "); } public static long totient(long n) { Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder()); long result = n; for (long p : factors) { result -= result / p; } return result; } interface BiFunctionResult<Type0, Type1, TypeResult> { TypeResult apply(Type0 x0, Type1 x1, TypeResult x2); } public static List<Integer> getGapsSingle(String string, char character) { List<Integer> result = new ArrayList<>(); Integer first = null; Integer last = null; for (int index = 0; index < string.length(); index++) { if (character == string.charAt(index)) { if (last == null) { first = index; } else { result.add(index - last); } last = index; } } if (first != null && first != last) { result.add(string.length() - (last - first)); } return result; } public static SortedSet<Integer> gaps(List<Integer> gaps) { SortedSet<Integer> result = new TreeSet(); for (Integer gap : gaps) { Set<Integer> next = new TreeSet(); next.add(gap); for (int existing : result) { next.add(existing + gap); } result.addAll(next); } return result; } public static int freq(String s, char c) { int result = 0; for (char x : s.toCharArray()) { if (x == c) { result += 1; } } return result; } public static int unique(String string, Set<Integer> positions, int shift) { int[] counts = new int[26]; for (int position : positions) { counts[string.charAt((position + shift) % string.length()) - 'a'] += 1; } int result = 0; for (int count : counts) { if (count == 1) { result += 1; } } return result; } public static int wins(String string, Set<Integer> positions) { int result = 0; for (int shift = 1; shift < string.length(); shift++) { result = Math.max(result, unique(string, positions, shift)); } return result; } public static void solve() throws IOException { String string = nextString(); Map<Character, Set<Integer>> letter2Positions = new TreeMap<>(); for (int index = 0; index < string.length(); index++) { char letter = string.charAt(index); Set<Integer> positions = letter2Positions.get(letter); if (positions == null) { positions = new TreeSet<>(); letter2Positions.put(letter, positions); } positions.add(index); } long wins = 0; for (Set<Integer> positions : letter2Positions.values()) { wins += wins(string, positions); } out.println((double) wins / string.length()); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
922525a83fc9f339f26f0243cbad2195
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; public class CF931_D2_E{ public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); String s=sc.next(); int n=s.length(); ArrayList<String> [] arr=new ArrayList [26]; for(int i=0;i<26;i++) arr[i]=new ArrayList<String>(); for(int i=0;i<n;i++){ s=s.substring(1)+s.charAt(0); arr[s.charAt(0)-'a'].add(s); } double ans=0; for(int i=0;i<26;i++){ int mx=0; for(int j=1;j<n;j++){ boolean [] v=new boolean [26]; boolean [] valid=new boolean [26]; Arrays.fill(valid, true); for(int k=0;k<arr[i].size();k++){ if(v[arr[i].get(k).charAt(j)-'a']) valid[arr[i].get(k).charAt(j)-'a']=false; v[arr[i].get(k).charAt(j)-'a']=true; } int cc=0; for(int ii=0;ii<26;ii++) if(v[ii] && valid[ii]) cc++; mx=Math.max(mx, cc); } ans+=(1.0*mx/n); } pw.println(ans); pw.flush(); pw.close(); } 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
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
9daff94ff96c14bb8b72919e6123f230
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; //http://codeforces.com/contest/931/problem/E public class GameWithString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] s = sc.nextLine().toCharArray(); sc.close(); double totalProb = 0; for (int i = 'a'; i <= 'z'; i++) { double curProb = 0; ArrayList<Integer> instances = new ArrayList<Integer>(); for (int j = 0; j < s.length; j++) { if (s[j] == i) { instances.add(j); } } if (!instances.isEmpty()) { for (int j = 1; j < s.length; j++) { Map<Character, Integer> seen = new HashMap<Character, Integer>(); for (int start : instances) { char nextLetter = s[(start + j) % s.length]; seen.put(nextLetter, seen.getOrDefault(nextLetter, 0) + 1); } int goodLetters = 0; for (int k : seen.values()) { if (k == 1) { goodLetters++; } } curProb = Math.max(curProb, (double)goodLetters / s.length); } } totalProb += curProb; } System.out.println(totalProb); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
f1fc8b0a3a1b80757d759c1ccee57c87
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.io.*; public class E { public static class alw { ArrayList<Integer> al; int c; public alw() { al = new ArrayList<Integer>(); c = 0; } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); char[] ree = in.readLine().toCharArray(); int siz = ree.length; alw[] arr = new alw[26]; for(int i = 0; i < 26; i++) arr[i] = new alw(); for(int i = 0; i < ree.length; i++) { //System.out.println("Adding to " + (ree[i]-'a')); arr[(ree[i]-'a')].al.add(i); arr[(ree[i]-'a')].c++; } int good = 0; for(int i = 0; i < 26; i++) { if(arr[i].c == 0) continue; else { int best = 0; for(int os = 1; os < ree.length; os++) { int[] chk = new int[26]; boolean gucci = true; for(int nnn : arr[i].al) { chk[(ree[(nnn + os) % siz] - 'a')]++; } int resss = 0; for(int ii = 0; ii < 26; ii++) { if(chk[ii] == 1) resss++; } if(resss > best) best = resss; } good += best; } } double ggg = (double) good; double total = (double) siz; double res = ggg / total; out.write(res + "\n"); out.flush(); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
49db027f670c6968b3ed08d9383b48df
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
//package baobab; import java.io.*; import java.util.*; public class E { public static final boolean DEBUG_PRINTS = false; public static void main(String[] args) { Solver solver = new Solver(); } static class Solver { IO io; public Solver() { this.io = new IO(); try { solve(); } catch (RuntimeException e) { if (!e.getMessage().equals("Clean exit")) { throw e; } } finally { io.close(); } } /****************************** START READING HERE ********************************/ void solve() { String s = io.next(); List<Integer>[] starts = new ArrayList[28]; for (int c='a'; c<='z'; c++) { starts[c-'a'] = new ArrayList<>(); } for (int i=0; i<s.length(); i++) { int c = s.charAt(i); starts[c-'a'].add(i); } double ans = 0; for (int c='a'; c<='z'; c++) { double bestChoice = 0; if (starts[c-'a'].size() == 0) { continue; } for (int dist=1; dist<s.length(); dist++) { int[] counts = new int[28]; for (int start : starts[c-'a']) { int nextPos = (start + dist) % s.length(); int nextChar = s.charAt(nextPos); counts[nextChar-'a']++; } int countGood = 0; int countBad = 0; for (int nextChar='a'; nextChar<='z'; nextChar++) { int count = counts[nextChar-'a']; if (count == 1) { countGood += count; } else { countBad += count; } } double currChoice = countGood * 1.0 / (countBad+countGood); bestChoice = Math.max(bestChoice, currChoice); } double probGettingCFirst = (starts[c-'a'].size() * 1.0 / s.length()); ans += (probGettingCFirst * bestChoice); } io.println(ans); } /************************** UTILITY CODE BELOW THIS LINE **************************/ long MOD = (long)1e9 + 7; List<Integer>[] toGraph(IO io, int n) { List<Integer>[] g = new ArrayList[n+1]; for (int i=1; i<=n; i++) g[i] = new ArrayList<>(); for (int i=1; i<=n-1; i++) { int a = io.nextInt(); int b = io.nextInt(); g[a].add(b); g[b].add(a); } return g; } class Point { int y; int x; public Point(int y, int x) { this.y = y; this.x = x; } } class IDval implements Comparable<IDval> { int id; long val; public IDval(int id, long val) { this.val = val; this.id = id; } @Override public int compareTo(IDval o) { if (this.val < o.val) return -1; if (this.val > o.val) return 1; return this.id - o.id; } } long pow(long base, int exp) { if (exp == 0) return 1L; long x = pow(base, exp/2); long ans = x * x; if (exp % 2 != 0) ans *= base; return ans; } long gcd(long... v) { /** Chained calls to Euclidean algorithm. */ if (v.length == 1) return v[0]; long ans = gcd(v[1], v[0]); for (int i=2; i<v.length; i++) { ans = gcd(ans, v[i]); } return ans; } long gcd(long a, long b) { /** Euclidean algorithm. */ if (b == 0) return a; return gcd(b, a%b); } int[] generatePrimesUpTo(int last) { /* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */ int[] div = new int[last+1]; for (int x=2; x<=last; x++) { if (div[x] > 0) continue; for (int u=2*x; u<=last; u+=x) { div[u] = x; } } return div; } long lcm(long a, long b) { /** Least common multiple */ return a * b / gcd(a,b); } private class ElementCounter { private HashMap<Long, Integer> elements; public ElementCounter() { elements = new HashMap<>(); } public void add(long element) { int count = 1; if (elements.containsKey(element)) count += elements.get(element); elements.put(element, count); } public void remove(long element) { int count = elements.get(element); count--; if (count == 0) elements.remove(element); else elements.put(element, count); } public int get(long element) { if (!elements.containsKey(element)) return 0; return elements.get(element); } public int size() { return elements.size(); } } class StringCounter { HashMap<String, Long> elements; public StringCounter() { elements = new HashMap<>(); } public void add(String identifier) { long count = 1; if (elements.containsKey(identifier)) count += elements.get(identifier); elements.put(identifier, count); } public void remove(String identifier) { long count = elements.get(identifier); count--; if (count == 0) elements.remove(identifier); else elements.put(identifier, count); } public long get(String identifier) { if (!elements.containsKey(identifier)) return 0; return elements.get(identifier); } public int size() { return elements.size(); } } class DisjointSet { /** Union Find / Disjoint Set data structure. */ int[] size; int[] parent; int componentCount; public DisjointSet(int n) { componentCount = n; size = new int[n]; parent = new int[n]; for (int i=0; i<n; i++) parent[i] = i; for (int i=0; i<n; i++) size[i] = 1; } public void join(int a, int b) { /* Find roots */ int rootA = parent[a]; int rootB = parent[b]; while (rootA != parent[rootA]) rootA = parent[rootA]; while (rootB != parent[rootB]) rootB = parent[rootB]; if (rootA == rootB) { /* Already in the same set */ return; } /* Merge smaller set into larger set. */ if (size[rootA] > size[rootB]) { size[rootA] += size[rootB]; parent[rootB] = rootA; } else { size[rootB] += size[rootA]; parent[rootA] = rootB; } componentCount--; } } class LCAFinder { /* O(n log n) Initialize: new LCAFinder(graph) * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */ int[] nodes; int[] depths; int[] entries; int pointer; FenwickMin fenwick; public LCAFinder(List<Integer>[] graph) { this.nodes = new int[(int)10e6]; this.depths = new int[(int)10e6]; this.entries = new int[graph.length]; this.pointer = 1; boolean[] visited = new boolean[graph.length+1]; dfs(1, 0, graph, visited); fenwick = new FenwickMin(pointer-1); for (int i=1; i<pointer; i++) { fenwick.set(i, depths[i] * 1000000L + i); } } private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) { visited[node] = true; entries[node] = pointer; nodes[pointer] = node; depths[pointer] = depth; pointer++; for (int neighbor : graph[node]) { if (visited[neighbor]) continue; dfs(neighbor, depth+1, graph, visited); nodes[pointer] = node; depths[pointer] = depth; pointer++; } } public int find(int a, int b) { int left = entries[a]; int right = entries[b]; if (left > right) { int temp = left; left = right; right = temp; } long mixedBag = fenwick.getMin(left, right); int index = (int) (mixedBag % 1000000L); return nodes[index]; } } class FenwickMin { long n; long[] original; long[] bottomUp; long[] topDown; public FenwickMin(int n) { this.n = n; original = new long[n+2]; bottomUp = new long[n+2]; topDown = new long[n+2]; } public void set(int modifiedNode, long value) { long replaced = original[modifiedNode]; original[modifiedNode] = value; // Update left tree int i = modifiedNode; long v = value; while (i <= n) { if (v > bottomUp[i]) { if (replaced == bottomUp[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i-x; v = Math.min(v, bottomUp[child]); } } else break; } if (v == bottomUp[i]) break; bottomUp[i] = v; i += (i&-i); } // Update right tree i = modifiedNode; v = value; while (i > 0) { if (v > topDown[i]) { if (replaced == topDown[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i+x; if (child > n+1) break; v = Math.min(v, topDown[child]); } } else break; } if (v == topDown[i]) break; topDown[i] = v; i -= (i&-i); } } public long getMin(int a, int b) { long min = original[a]; int prev = a; int curr = prev + (prev&-prev); // parent right hand side while (curr <= b) { min = Math.min(min, topDown[prev]); // value from the other tree prev = curr; curr = prev + (prev&-prev);; } min = Math.min(min, original[prev]); prev = b; curr = prev - (prev&-prev); // parent left hand side while (curr >= a) { min = Math.min(min,bottomUp[prev]); // value from the other tree prev = curr; curr = prev - (prev&-prev); } return min; } } class FenwickSum { public long[] d; public FenwickSum(int n) { d=new long[n+1]; } /** a[0] must be unused. */ public FenwickSum(long[] a) { d=new long[a.length]; for (int i=1; i<a.length; i++) { modify(i, a[i]); } } /** Do not modify i=0. */ void modify(int i, long v) { while (i<d.length) { d[i] += v; // Move to next uplink on the RIGHT side of i i += (i&-i); } } /** Returns sum from a to b, *BOTH* inclusive. */ long getSum(int a, int b) { return getSum(b) - getSum(a-1); } private long getSum(int i) { long sum = 0; while (i>0) { sum += d[i]; // Move to next uplink on the LEFT side of i i -= (i&-i); } return sum; } } class SegmentTree { /** Query sums with log(n) modifyRange */ int N; long[] p; public SegmentTree(int n) { /* TODO: Test that this works. */ for (N=2; N<n; N++) N *= 2; p = new long[2*N]; } public void modifyRange(int a, int b, long change) { muuta(a, change); muuta(b+1, -change); } void muuta(int k, long muutos) { k += N; p[k] += muutos; for (k /= 2; k >= 1; k /= 2) { p[k] = p[2*k] + p[2*k+1]; } } public long get(int k) { int a = N; int b = k+N; long s = 0; while (a <= b) { if (a%2 == 1) s += p[a++]; if (b%2 == 0) s += p[b--]; a /= 2; b /= 2; } return s; } } class Zalgo { public int pisinEsiintyma(String haku, String kohde) { char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); int max = 0; for (int i=haku.length(); i<z.length; i++) { max = Math.max(max, z[i]); } return max; } public int[] toZarray(char[] s) { int n = s.length; int[] z = new int[n]; int a = 0, b = 0; for (int i = 1; i < n; i++) { if (i > b) { for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++; } else { z[i] = z[i - a]; if (i + z[i - a] > b) { for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++; a = i; b = i + z[i] - 1; } } } return z; } public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) { // this is alternative use case char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); List<Integer> indexes = new ArrayList<>(); for (int i=haku.length(); i<z.length; i++) { if (z[i] < haku.length()) continue; indexes.add(i); } return indexes; } } class StringHasher { class HashedString { long[] hashes; long[] modifiers; public HashedString(long[] hashes, long[] modifiers) { this.hashes = hashes; this.modifiers = modifiers; } } long P; long M; public StringHasher() { initializePandM(); } HashedString hashString(String s) { int n = s.length(); long[] hashes = new long[n]; long[] modifiers = new long[n]; hashes[0] = s.charAt(0); modifiers[0] = 1; for (int i=1; i<n; i++) { hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; modifiers[i] = (modifiers[i-1] * P) % M; } return new HashedString(hashes, modifiers); } /** * Indices are inclusive. */ long getHash(HashedString hashedString, int startIndex, int endIndex) { long[] hashes = hashedString.hashes; long[] modifiers = hashedString.modifiers; long result = hashes[endIndex]; if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M; if (result < 0) result += M; return result; } // Less interesting methods below /** * Efficient for 2 input parameter strings in particular. */ HashedString[] hashString(String first, String second) { HashedString[] array = new HashedString[2]; int n = first.length(); long[] modifiers = new long[n]; modifiers[0] = 1; long[] firstHashes = new long[n]; firstHashes[0] = first.charAt(0); array[0] = new HashedString(firstHashes, modifiers); long[] secondHashes = new long[n]; secondHashes[0] = second.charAt(0); array[1] = new HashedString(secondHashes, modifiers); for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M; secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M; } return array; } /** * Efficient for 3+ strings * More efficient than multiple hashString calls IF strings are same length. */ HashedString[] hashString(String... strings) { HashedString[] array = new HashedString[strings.length]; int n = strings[0].length(); long[] modifiers = new long[n]; modifiers[0] = 1; for (int j=0; j<strings.length; j++) { // if all strings are not same length, defer work to another method if (strings[j].length() != n) { for (int i=0; i<n; i++) { array[i] = hashString(strings[i]); } return array; } // otherwise initialize stuff long[] hashes = new long[n]; hashes[0] = strings[j].charAt(0); array[j] = new HashedString(hashes, modifiers); } for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; for (int j=0; j<strings.length; j++) { String s = strings[j]; long[] hashes = array[j].hashes; hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; } } return array; } void initializePandM() { ArrayList<Long> modOptions = new ArrayList<>(20); modOptions.add(353873237L); modOptions.add(353875897L); modOptions.add(353878703L); modOptions.add(353882671L); modOptions.add(353885303L); modOptions.add(353888377L); modOptions.add(353893457L); P = modOptions.get(new Random().nextInt(modOptions.size())); modOptions.clear(); modOptions.add(452940277L); modOptions.add(452947687L); modOptions.add(464478431L); modOptions.add(468098221L); modOptions.add(470374601L); modOptions.add(472879717L); modOptions.add(472881973L); M = modOptions.get(new Random().nextInt(modOptions.size())); } } private static class Prob { /** For heavy calculations on probabilities, this class * provides more accuracy & efficiency than doubles. * Math explained: https://en.wikipedia.org/wiki/Log_probability * Quick start: * - Instantiate probabilities, eg. Prob a = new Prob(0.75) * - add(), multiply() return new objects, can perform on nulls & NaNs. * - get() returns probability as a readable double */ /** Logarithmized probability. Note: 0% represented by logP NaN. */ private double logP; /** Construct instance with real probability. */ public Prob(double real) { if (real > 0) this.logP = Math.log(real); else this.logP = Double.NaN; } /** Construct instance with already logarithmized value. */ static boolean dontLogAgain = true; public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) { this.logP = logP; } /** Returns real probability as a double. */ public double get() { return Math.exp(logP); } @Override public String toString() { return ""+get(); } /***************** STATIC METHODS BELOW ********************/ /** Note: returns NaN only when a && b are both NaN/null. */ public static Prob add(Prob a, Prob b) { if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); if (nullOrNaN(a)) return copy(b); if (nullOrNaN(b)) return copy(a); double x = Math.max(a.logP, b.logP); double y = Math.min(a.logP, b.logP); double sum = x + Math.log(1 + Math.exp(y - x)); return new Prob(sum, dontLogAgain); } /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */ public static Prob multiply(Prob a, Prob b) { if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); return new Prob(a.logP + b.logP, dontLogAgain); } /** Returns true if p is null or NaN. */ private static boolean nullOrNaN(Prob p) { return (p == null || Double.isNaN(p.logP)); } /** Returns a new instance with the same value as original. */ private static Prob copy(Prob original) { return new Prob(original.logP, dontLogAgain); } } public class StronglyConnectedComponents { /** Kosaraju's algorithm */ ArrayList<Integer>[] forw; ArrayList<Integer>[] bacw; /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */ public int getCount(int n, int[] mista, int[] minne) { forw = new ArrayList[n+1]; bacw = new ArrayList[n+1]; for (int i=1; i<=n; i++) { forw[i] = new ArrayList<Integer>(); bacw[i] = new ArrayList<Integer>(); } for (int i=0; i<mista.length; i++) { int a = mista[i]; int b = minne[i]; forw[a].add(b); bacw[b].add(a); } int count = 0; List<Integer> list = new ArrayList<Integer>(); boolean[] visited = new boolean[n+1]; for (int i=1; i<=n; i++) { dfsForward(i, visited, list); } visited = new boolean[n+1]; for (int i=n-1; i>=0; i--) { int node = list.get(i); if (visited[node]) continue; count++; dfsBackward(node, visited); } return count; } public void dfsForward(int i, boolean[] visited, List<Integer> list) { if (visited[i]) return; visited[i] = true; for (int neighbor : forw[i]) { dfsForward(neighbor, visited, list); } list.add(i); } public void dfsBackward(int i, boolean[] visited) { if (visited[i]) return; visited[i] = true; for (int neighbor : bacw[i]) { dfsBackward(neighbor, visited); } } } class DrawGrid { void draw(boolean[][] d) { System.out.print(" "); for (int x=0; x<d[0].length; x++) { System.out.print(" " + x + " "); } System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print((d[y][x] ? "[x]" : "[ ]")); } System.out.println(""); } } void draw(int[][] d) { int max = 1; for (int y=0; y<d.length; y++) { for (int x=0; x<d[0].length; x++) { max = Math.max(max, ("" + d[y][x]).length()); } } System.out.print(" "); String format = "%" + (max+2) + "s"; for (int x=0; x<d[0].length; x++) { System.out.print(String.format(format, x) + " "); } format = "%" + (max) + "s"; System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print(" [" + String.format(format, (d[y][x])) + "]"); } System.out.println(""); } } } class BaseConverter { /* Palauttaa luvun esityksen kannassa base */ public String convert(Long number, int base) { return Long.toString(number, base); } /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku StringinΓ€ kannassa baseFrom */ public String convert(String number, int baseFrom, int baseTo) { return Long.toString(Long.parseLong(number, baseFrom), baseTo); } /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */ public long longify(String number, int baseFrom) { return Long.parseLong(number, baseFrom); } } class Binary implements Comparable<Binary> { /** * Use example: Binary b = new Binary(Long.toBinaryString(53249834L)); * * When manipulating small binary strings, instantiate new Binary(string) * When just reading large binary strings, instantiate new Binary(string,true) * get(int i) returns a character '1' or '0', not an int. */ private boolean[] d; private int first; // Starting from left, the first (most remarkable) '1' public int length; public Binary(String binaryString) { this(binaryString, false); } public Binary(String binaryString, boolean initWithMinArraySize) { length = binaryString.length(); int size = Math.max(2*length, 1); first = length/4; if (initWithMinArraySize) { first = 0; size = Math.max(length, 1); } d = new boolean[size]; for (int i=0; i<length; i++) { if (binaryString.charAt(i) == '1') d[i+first] = true; } } public void addFirst(char c) { if (first-1 < 0) doubleArraySize(); first--; d[first] = (c == '1' ? true : false); length++; } public void addLast(char c) { if (first+length >= d.length) doubleArraySize(); d[first+length] = (c == '1' ? true : false); length++; } private void doubleArraySize() { boolean[] bigArray = new boolean[(d.length+1) * 2]; int newFirst = bigArray.length / 4; for (int i=0; i<length; i++) { bigArray[i + newFirst] = d[i + first]; } first = newFirst; d = bigArray; } public boolean flip(int i) { boolean value = (this.d[first+i] ? false : true); this.d[first+i] = value; return value; } public void set(int i, char c) { boolean value = (c == '1' ? true : false); this.d[first+i] = value; } public char get(int i) { return (this.d[first+i] ? '1' : '0'); } @Override public int compareTo(Binary o) { if (this.length != o.length) return this.length - o.length; int len = this.length; for (int i=0; i<len; i++) { int diff = this.get(i) - o.get(i); if (diff != 0) return diff; } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append(d[i+first] ? '1' : '0'); } return sb.toString(); } } class BinomialCoefficients { /** Total number of K sized unique combinations from pool of size N (unordered) N! / ( K! (N - K)! ) */ /** For simple queries where output fits in long. */ public long biCo(long n, long k) { long r = 1; if (k > n) return 0; for (long d = 1; d <= k; d++) { r *= n--; r /= d; } return r; } /** For multiple queries with same n, different k. */ public long[] precalcBinomialCoefficientsK(int n, int maxK) { long v[] = new long[maxK+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,maxK); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle } } return v; } /** When output needs % MOD. */ public long[] precalcBinomialCoefficientsK(int n, int k, long M) { long v[] = new long[k+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,k); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle v[j] %= M; } } return v; } } class Trie { int N; int Z; int nextFreeId; int[][] pointers; boolean[] end; /** maxLenSum = maximum possible sum of length of words */ public Trie(int maxLenSum, int alphabetSize) { this.N = maxLenSum; this.Z = alphabetSize; this.nextFreeId = 1; pointers = new int[N+1][alphabetSize]; end = new boolean[N+1]; } public void addWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) { next = nextFreeId++; pointers[curr][c] = next; } curr = next; } int last = word.charAt(word.length()-1) - 'a'; end[last] = true; } public boolean hasWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) return false; curr = next; } int last = word.charAt(word.length()-1) - 'a'; return end[last]; } } private class IO extends PrintWriter { private InputStreamReader r; private static final int BUFSIZE = 1 << 15; private char[] buf; private int bufc; private int bufi; private StringBuilder sb; public IO() { super(new BufferedOutputStream(System.out)); r = new InputStreamReader(System.in); buf = new char[BUFSIZE]; bufc = 0; bufi = 0; sb = new StringBuilder(); } /** Print, flush, return nextInt. */ private int queryInt(String s) { io.println(s); io.flush(); return nextInt(); } /** Print, flush, return nextLong. */ private long queryLong(String s) { io.println(s); io.flush(); return nextLong(); } /** Print, flush, return next word. */ private String queryNext(String s) { io.println(s); io.flush(); return next(); } private void fillBuf() throws IOException { bufi = 0; bufc = 0; while(bufc == 0) { bufc = r.read(buf, 0, BUFSIZE); if(bufc == -1) { bufc = 0; return; } } } private boolean pumpBuf() throws IOException { if(bufi == bufc) { fillBuf(); } return bufc != 0; } private boolean isDelimiter(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; } private void eatDelimiters() throws IOException { while(true) { if(bufi == bufc) { fillBuf(); if(bufc == 0) throw new RuntimeException("IO: Out of input."); } if(!isDelimiter(buf[bufi])) break; ++bufi; } } public String next() { try { sb.setLength(0); eatDelimiters(); int start = bufi; while(true) { if(bufi == bufc) { sb.append(buf, start, bufi - start); fillBuf(); start = 0; if(bufc == 0) break; } if(isDelimiter(buf[bufi])) break; ++bufi; } sb.append(buf, start, bufi - start); return sb.toString(); } catch(IOException e) { throw new RuntimeException("IO.next: Caught IOException."); } } public int nextInt() { try { int ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextInt: Invalid int."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int."); ret *= 10; ret -= (int)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int."); } else { throw new RuntimeException("IO.nextInt: Invalid int."); } ++bufi; } if(positive) { if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextInt: Caught IOException."); } } public long nextLong() { try { long ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextLong: Invalid long."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long."); ret *= 10; ret -= (long)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long."); } else { throw new RuntimeException("IO.nextLong: Invalid long."); } ++bufi; } if(positive) { if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextLong: Caught IOException."); } } public double nextDouble() { return Double.parseDouble(next()); } } void print(Object output) { io.println(output); } void done(Object output) { print(output); done(); } void done() { io.close(); throw new RuntimeException("Clean exit"); } long min(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } double min(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } int min(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } long max(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } double max(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } int max(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } void debug(Object output) { if (DEBUG_PRINTS) { System.out.println(output); } } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
fae4964cfce4b3d1ae6c909b00058393
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter pw = new PrintWriter(System.out); // long st = System.currentTimeMillis(); Tanks.solve(sc, pw); // pw.println(System.currentTimeMillis() - st); pw.close(); } public static class Tanks { static List<Integer>[] idxs; static int[] solus; static char[] str; static int n; public static void solve(MyScanner sc, PrintWriter pw) throws IOException { str = sc.next().toCharArray(); // str = new char[4]; // Random rnd = new Random(); // for (int i = 0; i < 4; i++) { //// str[i] = 'a'; // int c = (int)(rnd.nextDouble() * 26); // str[i] = (char)(c + 'a'); // } n = str.length; idxs = new List[26]; for (int i = 0; i < idxs.length; i++) { idxs[i] = new ArrayList<>(); } solus = new int[n]; for (int i = 0; i < n; i++) { str[i] -= 'a'; idxs[str[i]].add(i); } int su = 0; for (int i = 0; i < 26; i++) { if (idxs[i].size() == 0) continue; if (idxs[i].size() == 1) { // solus[idxs[i].get(0)] = 1; su += 1; continue; } int start = idxs[i].get(0); int bs = 0; for (int j = 1; j < n; j++) { boolean br = false; int cc = 0; int[] cnt = new int[26]; for (int k = 0; k < idxs[i].size(); k++) { int pt = (idxs[i].get(k) + j) % n; if (cnt[str[pt]] == 0) { cnt[str[pt]] = idxs[i].get(k) + 1; } else { cnt[str[pt]] = -1; } } for (int k = 0; k < 26; k++) { if (cnt[k] > 0) { cc++; // solus[cnt[k] - 1] = 1; } } bs = Math.max(bs, cc); } su += bs; } // for (int i = 0; i < n; i++) { // su += solus[i] == 1 ? 1 : 0; // } pw.println((su + 0.0) / n); } } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public MyScanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
ce406bd7cf1d9f1c729fa27960a41b50
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; public class R468_E { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws Exception { String s = readString(); ArrayList<ArrayList<Integer>> a = new ArrayList(); for(int i = 'a'; i <= 'z'; ++i) a.add(new ArrayList()); for(int i = 0; i < s.length(); ++i) { a.get(s.charAt(i)-'a').add(i); } int d = 0; for(ArrayList<Integer> b : a) { if(!b.isEmpty()) { int max = 0; for(int i = 1; i < s.length(); ++i) { int[] t = new int['z'-'a'+1]; for(int c : b) t[s.charAt((c+i)%s.length())-'a']++; int c = 0; for(int j = 0; j <= 'z'-'a'; ++j) if(t[j] == 1) ++c; max = Math.max(max, c); } d += max; } } System.out.println((double)d/s.length()); } static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } static long readLong() throws Exception { return Long.parseLong(readString()); } static double readDouble() throws Exception { return Double.parseDouble(readString()); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
ef704e58340ce3cdea7e74e3574f178f
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
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.ArrayList; import java.util.StringTokenizer; public class codeforces { public static void main(String[] args) { FS scan = new FS(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = scan.next().toCharArray(); int[][][] count = new int[26][26][s.length]; int[] let = new int[26]; for(int i=0;i<s.length;i++){ let[s[i]-'a']++; for(int j=1;j<s.length;j++){ int idx2 = (i+j)%s.length; count[s[i]-'a'][s[idx2]-'a'][j]++; } } double prob = 0; for(int i=0;i<26;i++){ if(let[i]==0)continue; int max = 0; for(int j=1;j<s.length;j++){ int tmp = 0; for(int k=0;k<26;k++) if(count[i][k][j]==1) tmp++; max = Math.max(tmp, max); } prob += (double)max /(double)s.length; } System.out.println(prob); out.close(); } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next(){ while(st==null||!st.hasMoreElements()){ try{st = new StringTokenizer(br.readLine());} catch(IOException e){e.printStackTrace();} } return st.nextToken(); } int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() { return Double.parseDouble(next());} } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
6aa4f764576473278dad5678298fe8f2
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _931E { } */ public class _931E { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution String s = in.read(); int n = s.length(); int[][][] pre = new int[26][n + 1][26]; int[] cc = new int[26]; for (int i = 0; i < n; i++) { cc[s.charAt(i) - 'a']++; for (int j = i + 1; j < n; j++) { pre[s.charAt(i) - 'a'][j - i][s.charAt(j) - 'a']++; } for (int j = 0; j < i; j++) { pre[s.charAt(i) - 'a'][n - i + j][s.charAt(j) - 'a']++; } } double[][] prob = new double[26][n + 1]; double[] max = new double[26]; for (int i = 0; i < 26; i++) { for (int j = 1; j < n; j++) { for (int k = 0; k < 26; k++) { if (pre[i][j][k] == 1) { prob[i][j] += 1.0 / cc[i]; } } if (prob[i][j] > max[i]) { max[i] = prob[i][j]; } } } double ans = 0; for (int i = 0; i < 26; i++) { ans += cc[i] * max[i]; } System.out.println(ans / n); // double ans = 0; // // int[] min = new int[26]; // int[] minc = new int[26]; // int[] cc = new int[26]; // // for (int i = 0; i < 26; i++) { // min[i] = n + 1; // } // // for (int i = 0; i < n; i++) { // int ic = s.charAt(i) - 'a'; // cc[ic]++; // int cmin = n + 1; // for (int j = i + 1; j < n; j++) { // int jc = s.charAt(j) - 'a'; // cmin = Math.min(pre[ic][jc][j - i], cmin); // } // for (int j = 0; j < i; j++) { // int jc = s.charAt(j) - 'a'; // cmin = Math.min(pre[ic][jc][n - i + j], cmin); // } // // if (cmin < min[ic]) { // min[ic] = cmin; // minc[ic] = 1; // } else if (cmin == min[ic]) { // minc[ic]++; // } // } // // for (int i = 0; i < 26; i++) { // ans += (double) minc[i] / (26.0 * min[i]); // } // System.out.println(ans); // end here } public static void main(String[] args) throws FileNotFoundException { (new _931E()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
65cac38a715feebf35189deeb4a40d12
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class E { public static void main(String[] args) { Scanner input = new Scanner(); StringBuilder output = new StringBuilder(); String s = input.next(); int n = s.length(); int[][][] seen = new int[26][n][26]; int[][] ones = new int[26][n]; for (int i = 0; i < n; i++) { int first = s.charAt(i) - 'a'; for (int j = 1; j < n; j++) { int second = s.charAt((i + j) % n) - 'a'; seen[first][j][second]++; if (seen[first][j][second] == 1) { ones[first][j]++; } else if (seen[first][j][second] == 2) { ones[first][j]--; } } } double prob = 0; for (int i = 0; i < 26; i++) { int total = 0; for (int j = 0; j < n; j++) { total = max(total, ones[i][j]); } prob += (double)(total) / (double)n; } System.out.println(prob); } private static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(Reader in) { br = new BufferedReader(in); } public Scanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } // end Scanner }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
e215244af16ad77613299ca8e822cbc8
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class d { public static void main(String[] Args) throws Exception { FS sc = new FS(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String s = sc.next(); int x = 0; int n = s.length(); int[][] cs = new int[26][n]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { Arrays.fill(cs[j], 0); } for (int j = 0; j < n; j++) if (s.charAt(j) == 'a' + i) { int k = j; int c = 0; int end = k - 1; if (j == 0) end = n - 1; while (k != end) { cs[s.charAt(k) - 'a'][c]++; k++; c++; if (k == n) k = 0; } cs[s.charAt(end) - 'a'][c]++; } int tx = 0; for (int j = 0; j < n; j++) { int y = 0; for (int k = 0; k < 26; k++) if (cs[k][j] == 1) y++; if (y > tx) tx = y; } x += tx; } out.println(x * 1.0 / n); out.close(); } public static class FS { BufferedReader br; StringTokenizer st; FS(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine()); } FS(File f) throws Exception { br = new BufferedReader(new FileReader(f)); st = new StringTokenizer(br.readLine()); } String next() throws Exception { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(br.readLine()); return next(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
21e42367340844c35bd6970ac1931f19
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); char[] s = sc.next().toCharArray(); int n = s.length; double prob[][][] = new double[26][n][26]; double[] freq = new double[26]; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { int ind = (i + j) % n; prob[s[i] - 'a'][j][s[ind] - 'a']++; } freq[s[i] - 'a']++; } double ans = 0; for(int i = 0; i < 26; ++i) { double maxp = 0; for(int j = 0; j < n; ++j) { double cnt = 0; for(int k = 0; k < 26; ++k) { if(prob[i][j][k] == 1) cnt++; } maxp = max(maxp, cnt); } ans += maxp; } ans = ans / (double)n; w.print(ans); w.close(); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
fd3003c3991dff6e390848a3ce525c5d
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
// package cf931; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.*; import java.util.function.Supplier; import java.util.stream.IntStream; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toMap; public class CFD { //E private static final String INPUT = "bbaabaabbb\n"; FastScanner sc; public static void main(String[] args) { new CFD().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); long s = System.currentTimeMillis(); solve(); System.out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public void solve() { char[] chars = sc.nextLine().toCharArray(); int n = chars.length; Map<Character, List<Integer>> places = new TreeMap<>(); for (int i = 0; i < n; i++) { places.computeIfAbsent(chars[i], ch -> new ArrayList<>()).add(i); } int res = 0; int[] chart = new int[26]; for (Map.Entry<Character, List<Integer>> entry : places.entrySet()) { int chance = 0; for (int i = 1; i < n; i++) { //shift Arrays.fill(chart, 0); int curChance = 0; for (int pos : entry.getValue()) { int count = ++chart[chars[(pos + i) % n] - 'a']; if (count == 1) curChance++; if (count == 2) curChance--; } if (curChance == entry.getValue().size()) { chance = curChance; break; } else { chance = Math.max(curChance, chance); } } res += chance; } System.out.println((double)res / n); } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static <T> T elvis(T obj, Supplier<T> defValue) { return obj == null ? defValue.get() : obj; } @SuppressWarnings("SameParameterValue") private static <T> T elvis(T obj, T defValue) { return obj == null ? defValue : obj; } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { 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 (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
b488f9737a2407d323fe13097086ba69
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* * * Comments Here * */ public class E000 { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; public static void main(String[] args) throws java.lang.Exception { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); /*/ File file = new File("src/in.txt"); try { br = new BufferedReader(FileReader(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } /**/ char[] input = br.readLine().toCharArray(); int l = input.length; int[][][] count = new int[26][l][26]; for(int start = 0; start < l; ++start) { char cs = input[start]; for(int disp = 0; disp < l; ++disp) { int end = (start+disp)%l; char ce = input[end]; ++count[cs-'a'][disp][ce-'a']; } } int num = 0; for(int i = 0; i < 26; ++i) { int best = 0; for(int j = 0; j < l ; ++j) { int curr = 0; for(int k = 0; k < 26; ++k){ if(count[i][j][k] == 1) ++curr; } best = Math.max(best, curr); } num += best; } double ans = (num*1.0)/input.length; bw.write(ans + "\n"); br.close(); bw.close(); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
ab56429472182864467ce0e04c592ce4
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class R468_E { FastScanner in; PrintWriter out; public void solve() { String s = in.next(); int n = s.length(); ArrayList<Integer> a[] = new ArrayList[26]; for (int i = 0; i < 26; i++) { a[i] = new ArrayList<Integer>(); } for (int i = 0; i < n; i++) { a[s.charAt(i) - 'a'].add(i); } double sum = 0; for (int i = 0; i < 26; i++) { if (a[i].isEmpty()) continue; boolean hit = false; double best = 0; for (int d = 1; d < n; d++) { HashMap<Character, Integer> found = new HashMap<Character, Integer>(); for (int x : a[i]) { if (!found.containsKey(s.charAt((x + d) % n))) { found.put(s.charAt((x + d) % n), 1); } else { found.put(s.charAt((x + d) % n), found.get(s.charAt((x + d) % n)) + 1); } } double lbest = 0; for (Character x : found.keySet()) { if (found.get(x) == 1) { lbest++; } } best = Math.max(best, lbest); } sum += best; // if (!hit) { // sum += 1D * a[i].size() / (n-1); // } } out.println(sum / n); } public void run() { in = new FastScanner(); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); out.close(); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new R468_E().run(); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
bbcac45fe5981a1bd56e13a0f5c393a7
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.IntUnaryOperator; /** * gl hf */ public class Main { static class MyRunnable implements Runnable { @Override public void run() { } public void start() { } } static class Task { PrintWriter out; String s; int n; public void solve(MyScanner in, PrintWriter out) { this.out = out; s = in.nextLine(); n = s.length(); double res = 0; for (char x = 'a'; x <= 'z'; x++) { List<Integer> startIndex = new ArrayList<>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == x) { startIndex.add(i); } } double probChar = ((double) startIndex.size()) / n; if (startIndex.size() > 0) { double maxProb = 0; for (int i = 1; i < n; i++) { // ???? maxProb = Math.max(maxProb, getProb(x, i, startIndex)); } // out.println("Cahr " + x + " max prob " + maxProb); res += maxProb * probChar; } } out.println(res); } private double getProb(char c, int offset, List<Integer> startIndex ) { if (startIndex.size() == 0) return 0; Map<Character, Integer> map = new HashMap<>(); for (Integer x: startIndex) { int ind = (x + offset) % n; char charAt = s.charAt(ind); int ct = map.getOrDefault(charAt, 0); map.put(charAt, ct + 1); } int uniq = 0; int sum = 0; for (Integer v: map.values()) { if (v == 1) { uniq+=v; } sum += v; } //if (uniq > 0) out.println("uniq " + uniq + " when " + c + " " +offset + " " + (uniq / sum)); return ((double) uniq )/ sum; } private boolean can(List<Integer> startIndex) { if (startIndex.size() == 0) return false; HashSet<Character> currentChars = new HashSet<>(); for (int offset = 1; offset < n; offset++) { currentChars.clear(); boolean wasSame = false; for (Integer i : startIndex) { char willAdd = s.charAt((i + offset) % n); if (currentChars.contains(willAdd)) { wasSame = true; break; } else { currentChars.add(willAdd); } } if (!wasSame) { out.println("Start ind " + startIndex + " w offset " + offset + " good"); return true; } } return false; } private void printArray(int[] arr) { //out.println("Printing arrray of size " + arr.length); for (int i = 0; i < arr.length; i++) { out.println("Arr[" + i + "] = " + arr[i]); } } } public static void main(String[] args) { MyScanner in = new MyScanner(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(in, out); out.close(); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
b36e6f74650f42e3628f9042226e059d
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.lang.*; import java.math.*; import java.util.*; public class E { public static void main(String[] args) { FastReader fr = new FastReader(); String str = fr.next(); int n = str.length(); ArrayList<ArrayList<Integer>> letterIndexes = new ArrayList<>(26); for(int i = 0; i < 26; i++){ letterIndexes.add(new ArrayList<>()); } for(int i = 0; i < n; i++){ letterIndexes.get(str.charAt(i)-'a').add(i); } double[] cond = new double[26]; for(int i = 0; i < 26; i++){ if(letterIndexes.get(i).size() == 0) continue; double max = 0; for(int k = 0; k < n; k++){ HashMap<Character, Integer> hm = new HashMap<>(); for(int j = 0; j < letterIndexes.get(i).size(); j++){ char c = str.charAt((letterIndexes.get(i).get(j)+k)%n); hm.put(c, hm.getOrDefault(c, 0)+1); } int count = 0; for(char c : hm.keySet()) if(hm.get(c)==1) count++; if(count > max) max = count; } cond[i] = max; } double prob = 0; for(int i = 0; i < 26; i++) prob+=cond[i]; System.out.println(prob/n); } } class FastReader{ BufferedReader br; StringTokenizer st; FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } 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; } } //source: http://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
e800cf89a7c22be5690049545f662bc7
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; import java.lang.StringBuilder; public class test3 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int l = s.length(); int[] ct = new int[26]; int[][] pos = new int[26][l]; for (int i = 0; i < l; i++) { int k = s.charAt(i) - 97; pos[k][ct[k]] = i; ct[k]++; } int max = -10000; int res = 0; int[] temp = new int[26]; for (int i = 0; i < 26; i++) { max = -10000; for (int delt = 1; delt < l; delt++) { int cur = 0; int m = 0; for (int j = 0; j < 26; j++) { temp[j] = 2; } for (int j = 0; j < ct[i]; j++) { m = s.charAt((pos[i][j] + delt)%l) - 97; if (temp[m] == 2) { cur++; temp[m] = 1; } else if (temp[m] == 1) { cur--; temp[m] = 0; } } if (max < cur) max = cur; } res+= max; } System.out.println((float)res / (float)l); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
01b2f0de1c538b6ac657dc546e66aa2c
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; void solve(){ //Enter code here utkarsh char[] c = ns().toCharArray(); int n = c.length; ArrayList <Integer> a[] = new ArrayList[26]; for(int i = 0; i < 26; i++) { a[i] = new ArrayList<>(); } for(int i = 0; i < n; i++) { a[c[i] - 'a'].add(i); } int b[] = new int[26]; int x = 0; int y, z; for(int i = 0; i < 26; i++) { if(a[i].isEmpty()) continue; if(a[i].size() == 1) { x++; continue; } z = 0; for(int j = 1; j < n; j++) { Arrays.fill(b, 0); for(int u : a[i]) { int k = (u + j) % n; k = c[k] - 'a'; b[k]++; } y = 0; for(int k = 0; k < 26; k++) { if(b[k] == 1) { y++; } } if(y > z) z = y; } x += z; } out.println((x + 0.0) / (n + 0.0)); } public static void main(String[] args) { new utkarsh().run(); } void run(){ is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte(){ if(ptr >= len){ ptr = 0; try{ len = is.read(input); }catch(IOException e){ throw new InputMismatchException(); } if(len <= 0){ return -1; } } return input[ptr++]; } boolean isSpaceChar(int c){ return !( c >= 33 && c <= 126 ); } int skip(){ int b = readByte(); while(b != -1 && isSpaceChar(b)){ b = readByte(); } return b; } char nc(){ return (char)skip(); } String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } int ni(){ int n = 0,b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } if(b == -1){ return -1; } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl(){ long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd(){ return Double.parseDouble(ns()); } float nf(){ return Float.parseFloat(ns()); } int[] na(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++){ a[i] = ni(); } return a; } char[] ns(int n){ char c[] = new char[n]; int i,b = skip(); for(i = 0; i < n; i++){ if(isSpaceChar(b)){ break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
d1575f1342466da80e0c750e7ec3a3fe
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.io.*; public class Main { void solve(){ s=ns().toCharArray(); int n=s.length; char ss[]=(new String(s)+new String(s)).toCharArray(); int cnt[][][]=new int[26][26][n+1]; int cnt2[]=new int[26]; for(int i=0;i<n;i++) cnt2[s[i]-'a']++; for(int i=0;i<n;i++){ for(int l=1;l<=n;l++){ int j=i+l-1; cnt[ss[i]-'a'][ss[j]-'a'][j-i]++; } } // shift(); // shift(); // shift(); // pw.println(s); // for(int i=0;i<n;i++) { // pw.println(cnt[s[0]-'a'][s[i]-'a'][i]); // } double ans=0; for(int i=0;i<26;i++){ int mx=0; for(int d=0;d<n;d++){ int k=0; for(int j=0;j<26;j++){ if(cnt[i][j][d]==1)k++; } mx=Math.max(mx,k); } ans+=mx; } ans/=n; pw.println(ans); } char s[]; void shift(){ int n=s.length; char ch=s[n-1]; for(int i=n-2;i>=0;i--){ s[i+1]=s[i]; } s[0]=ch; } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
0f0c36dc6e23b6929b732e867b560625
train_000.jsonl
1520177700
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i.Β e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class cfs468E { public static void main(String[] args) { FastScanner sc = new FastScanner(); StringBuilder sb = new StringBuilder(); char[] letters = sc.next().toCharArray(); int n = letters.length; int[] allLetterFreq = new int[26]; for (int i : letters) { allLetterFreq[i - 'a']++; } int[][][] freq = new int[26][26][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // j is the offset freq[letters[i] - 'a'][letters[((j+i)%n+n)%n] - 'a'][j]++; } } double sum = 0; for (int i = 0; i < 26; i++) { // given first letter is i // determine which offset j will give best information if (allLetterFreq[i] == 0) continue; int mostDistinct = 0; for (int j = 0; j < n; j++) { int distinct = 0; for (int k = 0; k < 26; k++) { if (freq[i][k][j] == 1) distinct++; } mostDistinct = Math.max(mostDistinct, distinct); } double toAdd = (allLetterFreq[i] / (n * 1.0)) * ((1.0 * mostDistinct) / allLetterFreq[i]); sum += toAdd; } sb.append(sum); System.out.print(sb); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["technocup", "tictictactac", "bbaabaabbb"]
2 seconds
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Java 8
standard input
[ "implementation", "probabilities", "math" ]
4c92218ccbab7d142c2cbb6dd54c510a
The only string contains the string s of length l (3 ≀ l ≀ 5000), consisting of small English letters only.
1,600
Print the only numberΒ β€” the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
standard output
PASSED
b2dc48893c2dd6fe174e24e0a437584a
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.io.*; public class a { static long mod = 1000000009; static char[][] res; public static void main(String[] args) throws IOException { //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); xs = new int[8]; ys = new int[8]; String[] orders = {"0123","0132","0213","0231","0312","0321", "1023","1032","1203","1230","1302","1320", "2013","2031","2103","2130","2301","2310", "3012","3021","3102","3120","3201","3210"}; for(int i = 0; i<8; i++) { xs[i] = input.nextInt(); ys[i] = input.nextInt(); } boolean found = false; for(int i = 0; i<8; i++) for(int j = 0; j<8; j++) for(int k = 0; k<8; k++) for(int l = 0; l<8; l++) { if(i==j||i==k||i==l||j==k||j==l||k==l) continue; int[] first = {i,j,k,l}; ArrayList<Integer> secondlist = new ArrayList<Integer>(); for(int m = 0; m<8; m++) if(m != i && m != j && m != k && m != l) secondlist.add(m); int[] second = new int[4]; for(int m = 0; m<4; m++) { second[m] = secondlist.get(m); } for(int x = 0; x<24; x++) { if(found) break; for(int y = 0; y<24; y++) { int[] sortedx = new int[4]; for(int z = 0; z<4; z++) sortedx[z] = first[orders[x].charAt(z)-'0']; int[] sortedy = new int[4]; for(int z = 0; z<4; z++) sortedy[z] = second[orders[y].charAt(z)-'0']; int dist = dist(sortedx[0], sortedx[1]); if(dist != dist(sortedx[1], sortedx[2])) continue; if(dist != dist(sortedx[3], sortedx[2])) continue; if(dist != dist(sortedx[0], sortedx[3])) continue; if(dist + dist != dist(sortedx[0], sortedx[2])) continue; int dist1 = dist(sortedy[0], sortedy[1]), dist2 = dist(sortedy[2], sortedy[1]); if(dist1 != dist(sortedy[2], sortedy[3])) continue; if(dist2 != dist(sortedy[3], sortedy[0])) continue; if(dist1+dist2 != dist(sortedy[0], sortedy[2])) continue; found = true; out.println("YES"); for(int xx: sortedx) out.print((xx+1)+" "); out.println(); for(int yy: sortedy) out.print((yy+1)+" "); break; } if(found) break; } if(found) break; } if(!found) out.println("NO"); out.close(); } static int[] xs, ys; static int dist(int a, int b) { return (xs[a]-xs[b])*(xs[a]-xs[b]) + (ys[a]-ys[b])*(ys[a]-ys[b]); } static long pow(long x, long p) { if(p==0) return 1; if((p&1) > 0) { return (x*pow(x, p-1))%mod; } long sqrt = pow(x, p/2); return (sqrt*sqrt)%mod; } static long gcd(long a, long b) { if(b==0) return a; return gcd(b, a%b); } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static String nextLine() throws IOException { return reader.readLine(); } } /* Sum Interval Tree - uses O(n) space Updates and queries over a range of values in log(n) time Note: If querying all elements, use difference array instead. */ static class IT { int[] left,right, val, a, b; IT(int n) { left = new int[4*n]; right = new int[4*n]; val = new int[4*n]; a = new int[4*n]; b = new int[4*n]; init(0,0, n); } int init(int at, int l, int r) { a[at] = l; b[at] = r; if(l==r) left[at] = right [at] = -1; else { int mid = (l+r)/2; left[at] = init(2*at+1,l,mid); right[at] = init(2*at+2,mid+1,r); } return at++; } //return the sum over [x,y] int get(int x, int y) { return go(x,y, 0); } int go(int x,int y, int at) { if(at==-1) return 0; if(x <= a[at] && y>= b[at]) return val[at]; if(y<a[at] || x>b[at]) return 0; return go(x, y, left[at]) + go(x, y, right[at]); } //add v to elements x through y void add(int x, int y, int v) { go3(x, y, v, 0); } void go3(int x, int y, int v, int at) { if(at==-1) return; if(y < a[at] || x > b[at]) return; val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v; go3(x, y, v, left[at]); go3(x, y, v, right[at]); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
7ccd795777ea56e355642d65652115dd
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } } private int d(Point a, Point b){ return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } private int dot(Point a, Point b, Point c){ int vx0 = a.x - b.x; int vy0 = a.y - b.y; int vx1 = c.x - b.x; int vy1 = c.y - b.y; int ret = (vx0 * vx1 + vy0 * vy1); return ret; } private boolean goodAngle(Point a, Point b, Point c, Point d){ if(dot(a, b, c) == 0 && dot(b, c, d) == 0 && dot(c, d, a) == 0&& dot(d, a, b) == 0)return true; return false; } private boolean sq(Point a, Point b, Point c, Point d){ //angle must be 90 degree int l = d(a, b); if(l == d(b, c) && l == d(c, d) && l == d(a, d) && goodAngle(a, b, c, d)) return true; return false; } private boolean rec(Point a, Point b, Point c, Point d){ //angle must be 90 degree if(d(a,b) == d(c, d) && d(a, d) == d(b, c) && goodAngle(a, b, c, d)) return true; return false; } private boolean check(){ if(sq(p[a[0]], p[a[1]], p[a[2]], p[a[3]]) && rec(p[a[4]], p[a[5]], p[a[6]], p[a[7]])) return true; return false; } Point[] p; int[] a; int N = 8; public void solve() throws IOException { p = new Point[8]; for(int i = 0; i < 8; i++){ p[i] = new Point(nextInt(), nextInt()); } a = new int[N]; for(int i = 0; i < N; i++) a[i] = i; boolean ok = false; do{ //out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4] + " " + a[5] + " " + a[6] + " " + a[7]); if(check()){ ok = true; break; } }while(nextPermutation()); if(ok){ out.println("YES"); out.println((a[0] + 1) + " " + (a[1] + 1) + " " + (a[2] + 1) + " " + (a[3] + 1)); out.println((a[4] + 1) + " " + (a[5] + 1) + " " + (a[6] + 1) + " " + (a[7] + 1)); } else{ out.println("NO"); } } private boolean nextPermutation(){ int i = N-2; while(i >= 0 && a[i] >= a[i+1]) i--; if(i < 0) return false; int j = N-1; while(a[i] >= a[j]) j--; int t = a[i]; a[i] = a[j]; a[j] =t; i++; j = N-1; while(i < j){ t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } return true; } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
e8bb53252ccb3e506bce5c331e011b08
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } final double EPS = 1e-9; class Point implements Comparable<Point>{ long x,y; public Point(long x, long y) { super(); this.x = x; this.y = y; } public double dist(Point o) { return sqrt( (x - o.x) * (x - o.x) + (y - o.y) * (y - o.y) ); } @Override public int compareTo(Point o) { if (x != o.x) return Long.compare(x, o.x); return Long.compare(y, o.y); } } long scalarMul(Point middle, Point a, Point b) { return (a.x - middle.x) * (b.x - middle.x) + (a.y - middle.y) * (b.y - middle.y); } boolean isRectangle(Point[] point) { sort(point); return (scalarMul(point[0], point[1], point[2]) == 0) && (scalarMul (point[3], point[1], point[2]) == 0); } boolean isSquare(Point[] point) { return isRectangle(point) && abs(point[3].dist(point[1]) - point[1].dist(point[0])) < EPS; } Point[] point = new Point[8]; int[] squareIndex = new int[4]; int[] rectangleIndex = new int[4]; Point[] square = new Point[4]; Point[] rectangle = new Point[4]; boolean[] used = new boolean[8]; boolean dfs (int p) { if(p == 4) { int k = 0; for(int i = 0; i < 8; i++) { boolean existIndex = false; for(int j = 0; j < 4; j++) { if(i == squareIndex[j]) existIndex = true; } if(!existIndex) { rectangleIndex[k++] = i; } } for(int i = 0; i < 4; i++) square[i] = point[squareIndex[i]]; for(int i = 0; i < 4; i++) rectangle[i] = point[rectangleIndex[i]]; // System.err.println("Sq: " + Arrays.toString(squareIndex) + " " + isSquare(square)); // System.err.println("Re: " + Arrays.toString(rectangleIndex) + " " + isRectangle(rectangle)); if(isRectangle(rectangle) && isSquare(square)) return true; } else { for(int i = 0; i < 8; i++) { if(!used[i]) { used[i] = true; squareIndex[p] = i; if ( dfs( p + 1 ) ) return true; used[i] = false; } } } return false; } private void solve() throws IOException { for(int i = 0; i < 8; i++) { point[i] = new Point(nextInt(), nextInt()); } // Point[] p = new Point[4]; // for(int i = 0; i < 4; i++) // p[i] = point[i]; // sort(p); // for(int i = 0; i < 4; i++) { // out.println(p[i].x + " " + p[i].y); // } // System.err.println(isSquare(p)); if(dfs(0)) { out.println("YES"); for(int i = 0; i < 4; i++) out.print((squareIndex[i] + 1) + " "); out.println(); for(int i = 0; i < 4; i++) out.print((rectangleIndex[i] + 1) + " "); out.println(); } else { out.println("NO"); } } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4e196aa61b4ba64f89273c59a5b0872f
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class Main { long b = 31; String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// int INF = Integer.MAX_VALUE / 10; long MODULO = 1000*1000*1000+7; void solve() throws IOException { int n = 8; Point[] points = new Point[n]; for (int i=0; i<n; ++i) points[i] = new Point(readInt(), readInt()); Point[] points1 = new Point[4]; Point[] points2 = new Point[4]; for (int mask=0; mask < 1<<n; ++mask){ if (Integer.bitCount(mask) == 4){ int cur1 = 0; int cur2 = 0; for (int bit=0; bit<n; ++bit){ if (checkBit(mask, bit) == 1) points1[cur1++] = points[bit]; else points2[cur2++] = points[bit]; } boolean isSquare = checkSquare(points1[0], points1[1], points1[2], points1[3]) || checkSquare(points1[0], points1[2], points1[1], points1[3]) || checkSquare(points1[0], points1[1], points1[3], points1[2]) || checkSquare(points1[0], points1[2], points1[3], points1[1]) || checkSquare(points1[0], points1[3], points1[1], points1[2]) || checkSquare(points1[0], points1[3], points1[2], points1[1]); boolean isRecktangle = checkRecktangle(points2[0], points2[1], points2[2], points2[3]) || checkRecktangle(points2[0], points2[2], points2[1], points2[3]) || checkRecktangle(points2[0], points2[1], points2[3], points2[2]) || checkRecktangle(points2[0], points2[2], points2[3], points2[1]) || checkRecktangle(points2[0], points2[3], points2[2], points2[1]) || checkRecktangle(points2[0], points2[3], points2[1], points2[2]); // out.println(isRecktangle +" " + isSquare); if (isSquare && isRecktangle){ out.println("YES"); for (int bit=0; bit<n; ++bit) if (checkBit(mask, bit) == 1) out.print(bit+1+" "); out.println(); for (int bit=0; bit<n; ++bit) if (checkBit(mask, bit) == 0) out.print(bit+1+" "); return; } } } out.println("NO"); } boolean checkRecktangle(Point p1, Point p2, Point p3, Point p4){ int len1 = (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y); int len2 = (p3.x - p4.x)*(p3.x - p4.x) + (p3.y - p4.y)*(p3.y - p4.y); int v1X = p2.x - p1.x; int v1Y = p2.y - p1.y; int v2X = p4.x - p3.x; int v2Y = p4.y - p3.y; int v3X = p4.x - p1.x; int v3Y = p4.y - p1.y; int v4X = p3.x - p2.x; int v4Y = p3.y - p2.y; int mul1 = v1X*v2Y - v1Y*v2X; int mul2 = v3X*v2X + v3Y*v2Y; int mul3 = v4X*v2X + v4Y*v2Y; return len1 == len2 && mul1 == 0 && mul2 == 0 && mul3 == 0; } boolean checkSquare(Point p1, Point p2, Point p3, Point p4){ int len1 = (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y); int len2 = (p3.x - p4.x)*(p3.x - p4.x) + (p3.y - p4.y)*(p3.y - p4.y); int len3 = (p4.x - p1.x)*(p4.x - p1.x) + (p4.y - p1.y)*(p4.y - p1.y); int len4 = (p2.x - p3.x)*(p2.x - p3.x) + (p2.y - p3.y)*(p2.y - p3.y); int v1X = p2.x - p1.x; int v1Y = p2.y - p1.y; int v2X = p4.x - p3.x; int v2Y = p4.y - p3.y; int v3X = p4.x - p1.x; int v3Y = p4.y - p1.y; int mul1 = v1X*v2Y - v1Y*v2X; int mul2 = v3X*v2X + v3Y*v2Y; // out.println(len1 +" "+len2 +" "+ len3 +" "+ len4 +" " + mul1 +" " + mul2); return len1 == len2 && len1 == len3 && len1 == len4 && mul1 == 0 && mul2 == 0; } class Move{ int car, x, y; Move(int car, int x, int y){ this.x = x; this.y = y; this.car = car; } } class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } } class Vertex implements Comparable<Vertex>{ int dist, from; Vertex(int b, int c){ this.dist = c; this.from = b; } @Override public int compareTo(Vertex o) { return this.dist-o.dist; } } /////////////////////////////////////////////////////////////////////////////////////////// class Edge{ int from, to, dist; Edge(int from, int to, int dist){ this.from = from; this.to = to; this.dist = dist; } } void readUndirectedGraph (int n, int m, int[][] graph) throws IOException{ Edge[] edges = new Edge[n-1]; int[] countEdges = new int[n]; graph = new int[n][]; for (int i=0; i<n-1; ++i){ int from = readInt() - 1; int to = readInt() - 1; countEdges[from]++; countEdges[to]++; edges[i] = new Edge(from, to, 0); } for (int i=0; i<n; ++i) graph[i] = new int[countEdges[i]]; for (int i=0; i<n-1; ++i){ graph[edges[i].to][--countEdges[edges[i].to]] = edges[i].dist; graph[edges[i].dist][-- countEdges[edges[i].dist]] = edges[i].to; } } class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } class Dsu{ int[] parent; int countSets; Dsu(int n){ countSets = n; parent = new int[n]; for(int i=0; i<n; ++i){ parent[i] = i; } } int findSet(int a){ if(parent[a] == a) return a; parent[a] = findSet(parent[a]); return parent[a]; } void unionSets(int a, int b){ a = findSet(a); b = findSet(b); if(a!=b){ countSets--; parent[a] = b; } } } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } //////////////////////////////////////////////////////////// class SegmentTree{ int[] t; int n; SegmentTree(int n){ t = new int[4*n]; build(new int[n+1], 1, 1, n); } void build (int a[], int v, int tl, int tr) { if (tl == tr) t[v] = a[tl]; else { int tm = (tl + tr) / 2; build (a, v*2, tl, tm); build (a, v*2+1, tm+1, tr); } } void update (int v, int tl, int tr, int l, int r, int add) { if (l > r) return; if (l == tl && tr == r) t[v] += add; else { int tm = (tl + tr) / 2; update (v*2, tl, tm, l, Math.min(r,tm), add); update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add); } } int get (int v, int tl, int tr, int pos) { if (tl == tr) return t[v]; int tm = (tl + tr) / 2; if (pos <= tm) return t[v] + get (v*2, tl, tm, pos); else return t[v] + get (v*2+1, tm+1, tr, pos); } } class Fenwik { long[] t; int length; Fenwik(int[] a) { length = a.length + 100; t = new long[length]; for (int i = 0; i < a.length; ++i) { inc(i, a[i]); } } void inc(int ind, int delta) { for (; ind < length; ind = ind | (ind + 1)) { t[ind] = Math.max(delta, t[ind]); } } long getMax(int r) { long sum = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { sum = Math.max(sum, t[r]); } return sum; } } int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Random rnd = new Random(); Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
c89fbb48c36b045b2f835113bf483df7
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class RectSquare{ int[] x, y; public static void main(String[] args) { new RectSquare().run(); } public void run() { Scanner file = new Scanner(System.in); x = new int[8]; y = new int[8]; for(int i = 0;i<8;i++) { x[i] = file.nextInt(); y[i] = file.nextInt(); } for(int i = 0;i<8;i++) { for(int j = 0;j<8;j++) { if(i == j) continue; for(int k = 0;k<8;k++) { if(i == k || j == k) continue; for(int l = 0;l<8;l++) { if(i == l || j == l || k == l) continue; for(int m = 0;m<8;m++) { if(i == m || j == m || k == m || l == m) continue; for(int n = 0;n<8;n++) { if(i == n || j == n || k ==n || l == n || m == n) continue; for(int o = 0;o<8;o++) { if(i == o || j == o || k == o || l == o || m == o || n == o) continue; for(int p = 0;p<8;p++) { if(i == p || j == p || k == p || l == p || m == p || n == p || o == p) continue; int squaretl = i; int squaretr = j; int squarebl = k; int squarebr = l; int recttl = m; int recttr = n; int rectbl = o; int rectbr = p; double sideLen = dist(squaretl, squaretr); double root2 = Math.sqrt(2.0); boolean square = close(dist(squaretl,squaretr),sideLen) && close(dist(squaretl,squarebl),sideLen) && close(dist(squaretl,squarebr),sideLen*root2) && close(dist(squaretr,squarebr),sideLen) && close(dist(squaretr,squarebl),sideLen*root2) && close(dist(squarebl,squarebr),sideLen); double horzSide = dist(recttl, recttr); double vertSide = dist(recttl, rectbl); double diag = Math.hypot(horzSide, vertSide); boolean rect = close(dist(rectbl, rectbr), horzSide) && close(dist(recttr, rectbr), vertSide) && close(dist(recttl, rectbr), diag) && close(dist(recttr, rectbl), diag) && horzSide * vertSide != 0; if(square && rect) { System.out.println("YES"); System.out.printf("%d %d %d %d%n", i+1, j+1, k+1, l+1); System.out.printf("%d %d %d %d%n", m+1, n+1, o+1, p+1); return; } } } } } } } } } System.out.println("NO"); } boolean close(double x, double y) { return Math.abs(x-y) < .00000001; } double dist(int i, int j) { return Math.hypot(Math.abs(x[i]-x[j]), Math.abs(y[i] - y[j])); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
c75ab416e1a2d14009b0daa11bf16254
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { //static final long MOD = 998244353; static final long MOD = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(); int[][] points = new int[8][2]; for (int i = 0; i < 8; i++) { points[i][0] = sc.nextInt(); points[i][1] = sc.nextInt(); } for (int i = 0; i < (1<<8); i++) { ArrayList<Integer> subset = new ArrayList<Integer>(); for (int j = 0; j < 8; j++) { if ((i & (1 << j)) > 0) subset.add(j); } if (subset.size() == 4) { boolean square = true; for (int k = 0; k < 4; k++) { int[] dists = new int[3]; for (int a = 0; a < 3; a++) { dists[a] = dist(points[subset.get(k)],points[subset.get((k+a+1)%4)]); } Arrays.sort(dists); if (dists[0] != dists[1] || dists[2] != 2*dists[0]) { square = false; break; } } if (square) { ArrayList<Integer> rec = new ArrayList<Integer>(); for (int j = 0; j < 8; j++) { if ((i & (1 << j)) == 0) rec.add(j); } boolean isRec = true; for (int k = 0; k < 4; k++) { int[] dists = new int[3]; for (int a = 0; a < 3; a++) { dists[a] = dist(points[rec.get(k)],points[rec.get((k+a+1)%4)]); } Arrays.sort(dists); if (dists[2] != dists[0]+dists[1]) { isRec = false; break; } } if (isRec) { System.out.println("YES"); for (int x = 0; x < 4; x++) System.out.print((subset.get(x)+1) + " "); System.out.println(); for (int x = 0; x < 4; x++) System.out.print((rec.get(x)+1) + " "); System.out.println(); return; } } } } System.out.println("NO"); } public static int dist(int[] point, int[] point2) { return (int)(Math.pow((point2[1]-point[1]),2)+Math.pow((point2[0]-point[0]),2)); } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b,a%b); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { if (arr1[0] != arr2[0]) return arr1[0]-arr2[0]; else return arr1[1]-arr2[1]; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 8
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
5b5e4207882de50d29f5f4cb0ee50d70
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Scanner; public class sample { static int[] x = new int[8]; static int[] y = new int[8]; static double eps = 1e-8; static boolean found = false; public static void main(String[] args) { Scanner in = new Scanner(System.in); for (int i = 0; i < 8; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } perm(new int[8], new boolean[8], 0); if (!found) System.out.println("NO"); } public static void perm(int[] a, boolean[] v, int at) { if (found) return; if (at == 8) { int[] A = { x[a[0]], y[a[0]] }; int[] B = { x[a[1]], y[a[1]] }; int[] C = { x[a[2]], y[a[2]] }; int[] D = { x[a[3]], y[a[3]] }; int[] i = { x[a[4]], y[a[4]] }; int[] j = { x[a[5]], y[a[5]] }; int[] k = { x[a[6]], y[a[6]] }; int[] h = { x[a[7]], y[a[7]] }; if (isSquare(A, B, C, D) && isRect(i, j, k, h)) { System.out.println("YES"); System.out.printf("%d %d %d %d\n", a[0] + 1, a[1] + 1, a[2] + 1, a[3] + 1); System.out.printf("%d %d %d %d\n", a[4] + 1, a[5] + 1, a[6] + 1, a[7] + 1); found = true; return; } } for (int i = 0; i < v.length; i++) { if (!v[i]) { v[i] = true; a[at] = i; perm(a, v, at + 1); v[i] = false; } } } public static boolean isSquare(int[] A, int[] B, int[] C, int[] D) { double dist = dist(A, B); if (equals(dist, dist(B, C)) && equals(dist, dist(C, D)) && equals(dist, dist(D, A))) return isRect(A, B, C, D); return false; } public static boolean equals(double a, double b) { return Math.abs(a - b) <= eps; } public static boolean isRect(int[] A, int[] B, int[] C, int[] D) { if (dot(A, B, C) == 0 && dot(B, C, D) == 0 && dot(C, D, A) == 0 && dot(D, A, B) == 0) { int cross = cross(A, B, D); if (cross == cross(B, C, A) && cross == cross(C, D, B) && cross == cross(D, A, C)) return true; } return false; } public static int dot(int[] A, int[] B, int[] C) { // three points int[] AB = new int[2]; int[] BC = new int[2]; AB[0] = B[0] - A[0]; AB[1] = B[1] - A[1]; BC[0] = C[0] - B[0]; BC[1] = C[1] - B[1]; int dot = AB[0] * BC[0] + AB[1] * BC[1]; return dot; } public static int cross(int[] A, int[] B, int[] C) { // three points int[] AB = new int[2]; int[] AC = new int[2]; AB[0] = B[0] - A[0]; AB[1] = B[1] - A[1]; AC[0] = C[0] - A[0]; AC[1] = C[1] - A[1]; return AB[0] * AC[1] - AB[1] * AC[0]; } public static double dist(int[] A, int[] B) { // 2 points int a = A[0] - B[0]; int b = A[1] - B[1]; return Math.hypot(a, b); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
35abfda590bb9000f56fff3904b7f4f2
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.math.*; public class Main{ static boolean checkCross(int x0, int x1, int x2, int x3, int y0, int y1, int y2, int y3){ int check = (x1 - x0) * (x3 - x2) + (y1 - y0) * (y3 - y2); return check == 0; } static boolean isSquare(int[] x, int[] y){ boolean test = true; int[] add = new int[4]; for(int i = 1; i < 4; i++){ for(int j = 1; j < 4; j++){ if(i == j){ continue; } for(int k = 1; k < 4; k++){ if(j == k || i == k){ continue; } add[1] = i; add[2] = j; add[3] = k; test = true; for(int a = 0; a < 4; a++){ test &= checkCross(x[add[a]], x[add[(a + 1) % 4]], x[add[(a + 1) % 4]], x[add[(a + 2) % 4]], y[add[a]], y[add[(a + 1) % 4]], y[add[(a + 1) % 4]], y[add[(a + 2) % 4]]); } if(test){ if((Math.abs(x[add[1]] - x[add[0]]) == Math.abs(y[add[2]] - y[add[1]])) && (Math.abs(y[add[1]] - y[add[0]]) == Math.abs(x[add[2]] - x[add[1]]))){ return true; } } } } } return false; } static boolean isRectangle(int[] x, int[] y){ boolean test = true; int[] add = new int[4]; for(int i = 1; i < 4; i++){ for(int j = 1; j < 4; j++){ if(i == j){ continue; } for(int k = 1; k < 4; k++){ if(j == k || i == k){ continue; } add[1] = i; add[2] = j; add[3] = k; test = true; for(int a = 0; a < 4; a++){ test &= checkCross(x[add[a]], x[add[(a + 1) % 4]], x[add[(a + 1) % 4]], x[add[(a + 2) % 4]], y[add[a]], y[add[(a + 1) % 4]], y[add[(a + 1) % 4]], y[add[(a + 2) % 4]]); } if(test){ return true; } } } } return false; } static int[] getArray(int[] arr, boolean[] type, boolean match){ int count = 0; for(int i = 0; i < arr.length; i++){ if(type[i] == match){ count++; } } if(count == 4){ int[] res = new int[4]; for(int i = 0, j = 0; i < arr.length; i++){ if(type[i] == match){ res[j++] = arr[i]; } } return res; } return null; } static boolean search(boolean[] type, int[] x, int[] y, int index){ if(index == 8){ if(Arrays.equals(type, new boolean[]{false, false, false, false, true, true, true, true})){ int a = 0; } int[] tx = getArray(x, type, true); int[] ty = getArray(y, type, true); if(tx == null || !isSquare(tx, ty)){ return false; } tx = getArray(x, type, false); ty = getArray(y, type, false); return isRectangle(tx, ty); } type[index] = true; if(search(type, x, y, index + 1)){ return true; } type[index] = false; return search(type, x, y, index + 1); } public static void main(String[] args) throws Exception{ Scanner scan = new Scanner(System.in); int[] x = new int[8]; int[] y = new int[8]; for(int i = 0; i < 8; i++){ x[i] = scan.nextInt(); y[i] = scan.nextInt(); } boolean[] type = new boolean[8]; boolean res = search(type, x, y, 0); if(res){ System.out.println("YES"); boolean space = false; for(int i = 0; i < 8; i++){ if(type[i]){ if(space){ System.out.print(" "); } space = true; System.out.print(i + 1); } } System.out.println(); space = false; for(int i = 0; i < 8; i++){ if(!type[i]){ if(space){ System.out.print(" "); } space = true; System.out.print(i + 1); } } System.out.println(); } else{ System.out.println("NO"); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4c71d14cac956c4416e406f33684a0b5
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main implements Runnable { private void solution() throws IOException { int[] x = new int[8]; int[] y = new int[8]; for (int i = 0; i < x.length; ++i) { x[i] = in.nextInt(); y[i] = in.nextInt(); } int resMask = -1; for (int mask = 0; mask < (1 << 8); ++mask) { if (Integer.bitCount(mask) == 4) { if (isSqure(mask, x, y) && isRect(((1 << 8) - 1) ^ mask, x, y)) { resMask = mask; break; } } } if (resMask == -1) { out.println("NO"); } else { out.println("YES"); out(resMask); out(((1 << 8) - 1) ^ resMask); } } private boolean isRect(int mask, int[] x, int[] y) { int[] px = new int[4]; int[] py = new int[4]; int ls = 0; for (int i = 0; i < 8; ++i) { if (((mask >> i) & 1) != 0) { px[ls] = x[i]; py[ls] = y[i]; ++ls; } } return isRect(px, py); } private boolean isSqure(int mask, int[] x, int[] y) { int[] px = new int[4]; int[] py = new int[4]; int ls = 0; for (int i = 0; i < 8; ++i) { if (((mask >> i) & 1) != 0) { px[ls] = x[i]; py[ls] = y[i]; ++ls; } } if (!isRect(px, py)) { return false; } double len = dist(0, 1, px, py); for (int i = 1; i < 4; ++i) { if (Math.abs(len - dist(i, (i + 1) % 4, px, py)) > 1e-9) { return false; } } return true; } private double dist(int i, int j, int[] px, int[] py) { return (px[i] - px[j]) * (px[i] - px[j]) + (py[i] - py[j]) * (py[i] - py[j]); } private boolean isRect(int[] x, int[] y) { for (int i = 0; i < x.length; ++i) { for (int j = 0; j < x.length; ++j) { if (compare(i, j, x, y) > 0) { int tmp = x[i]; x[i] = x[j]; x[j] = tmp; tmp = y[i]; y[i] = y[j]; y[j] = tmp; } } } for (int i = 0; i < 4; ++i) { if (!valid((i - 1 + 4) % 4, i, (i + 1) % 4, x, y)) { return false; } } return true; } private boolean valid(int i, int j, int k, int[] x, int[] y) { int x1 = x[i] - x[j]; int y1 = y[i] - y[j]; int x2 = x[k] - x[j]; int y2 = y[k] - y[j]; return (x1 * x2 + y1 * y2) == 0; } private int compare(int i, int j, int[] x, int[] y) { return Double.compare((x[i] - x[0]) * (y[j] - y[0]) - (x[j] - x[0]) * (y[i] - y[0]), 0); } private void out(int mask) { boolean space = false; for (int i = 0; i < 8; ++i) { if (((mask >> i) & 1) != 0) { if (space) { out.print(' '); } else { space = true; } out.print((i + 1)); } } out.println(); } @Override public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { StringTokenizer tokenizer; BufferedReader reader; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } public static void main(String[] args) { new Thread(null, new Main(), "", 1 << 28).start(); } Scanner in = new Scanner(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
5e8dd07c6707f1b88ea51cbbc30eb28e
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class TaskD { /** * @param args */ public static void main(String[] args) { TaskD task = new TaskD(); task.read(); task.write(); } boolean was[] = new boolean[8]; int perm[] = new int[8]; int ax[] = new int[8]; int ay[] = new int[8]; boolean fullResult[] = new boolean[8]; boolean res = false; int kp[] = new int[4]; int n = 8; public void read() { Scanner in = new Scanner(System.in); for (int i = 0; i < n; i++) { ax[i] = in.nextInt(); ay[i] = in.nextInt(); } in.close(); } private long dist(int q, int w) { return (ax[q] - ax[w]) * (ax[q] - ax[w]) + (ay[q] - ay[w]) * (ay[q] - ay[w]); } private long dirSq() { long s = 0; for (int i = 0; i < 4; i++) { s += ax[kp[i]] * ay[kp[(1 + i) % 4]] - ax[kp[(1 + i) % 4]] * ay[kp[i]]; } return s; } private boolean checkQuadro() { long d = dist(kp[0], kp[3]); for (int i = 0; i < 3; i++) { if (d != dist(kp[i], kp[1 + i])) { return false; } } if (d == 0) { return false; } return 2 * d == Math.abs(dirSq()); } private boolean checkPryam() { long d1 = dist(kp[0], kp[3]); long d2 = dist(kp[0], kp[1]); if (d1 != dist(kp[1], kp[2]) || d2 != dist(kp[2], kp[3])) { return false; } if (d1 == 0 || d2 == 0) { return false; } return 4 * d1 * d2 == Math.abs(dirSq()) * Math.abs(dirSq()); } private boolean genPerm(ArrayList<Integer> start, int q, boolean was[], boolean isQuadro) { if (q == 4) { if (isQuadro) { return checkQuadro(); } else { return checkPryam(); } } boolean fl = false; for (int i = 0; i < 4; i++) { if (!was[start.get(i)]) { was[start.get(i)] = true; kp[q] = start.get(i); fl = fl || genPerm(start, 1 + q, was, isQuadro); was[start.get(i)] = false; } } return fl; } private boolean check() { ArrayList<Integer> quadro = new ArrayList<Integer>(); ArrayList<Integer> pry = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (was[i]) { quadro.add(i); } else { pry.add(i); } } boolean w[] = new boolean[8]; if (genPerm(quadro, 0, w, true) && genPerm(pry, 0, w, false)) { return true; } return false; } private void rec(int q) { if (q == 4) { if (check()) { res = true; for (int i = 0; i < n; i++) { fullResult[i] = was[i]; } } return; } for (int i = 0; i < n; i++) { if (!was[i]) { was[i] = true; rec(1 + q); was[i] = false; } } } public void write() { PrintWriter out = new PrintWriter(System.out); rec(0); if (res) { out.println("YES"); for (int i = 0; i < n; i++) { if (fullResult[i]) { out.print(1 + i + " "); } } out.println(); for (int i = 0; i < n; i++) { if (!fullResult[i]) { out.print(1 + i + " "); } } } else { out.println("NO"); } out.close(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
6c91c8579c213e7091abafa6355df8bf
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.geom.Line2D; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C97P4 { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; static int [] x = new int[9]; static int [] y = new int[9]; public static void main(String[] args) throws IOException { //------------------------------------------------------------------------- //Initializing... new C97P4(); //------------------------------------------------------------------------- //put your code here... :) for (int i = 1; i < 9; i++) { x[i]=nextInt(); y[i]=nextInt(); } boolean c = can(0); if(c){ writeln("YES"); for (int j = 0; j < 4; j++) { write(perm[j]+((j+1==4)?"\n":" ")); } for (int j = 4; j < 8; j++) { write(perm[j]+((j+1==8)?"\n":" ")); } }else writeln("NO"); //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } static int [] perm = new int[8]; static boolean [] vis =new boolean[9]; static boolean can(int l){ if(l==8)return check(); boolean res=false; for (int i = 1; i < 9; i++) { if(!vis[i]){ vis[i]=true; perm[l]=i; res|=can(l+1); if(res)return true;; vis[i]=false; } } return res; } private static boolean check() { // TODO Auto-generated method stub for (int i = 0; i < 4; i++) { if(!angle90s(perm[i],perm[ (i+1)%4], perm[(i+2)%4]))return false; } for (int i = 4; i < 8; i++) { if(!angle90(perm[i], perm[(i+1==8)?4:i+1], perm[(i+2==9)?5:(i+2==8)?4:i+2]))return false; } return true; } private static boolean angle90s(int i , int j , int k){ int aa = (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); int bb = (x[j]-x[k])*(x[j]-x[k])+(y[j]-y[k])*(y[j]-y[k]); int cc = (x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]); return aa+bb==cc&&aa==bb; } private static boolean angle90(int i , int j , int k){ int aa = (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); int bb = (x[j]-x[k])*(x[j]-x[k])+(y[j]-y[k])*(y[j]-y[k]); int cc = (x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]); return aa+bb==cc; } public C97P4() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+"\n"); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
b5cabac009f44bc7b8f3bc237e6a9eb6
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public final FastScanner in; public final PrintWriter out; public Main(String mode) throws IOException { if (mode.equals("console")) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new BufferedWriter(new FileWriter(new File( "output.txt")))); } } public void close() throws IOException { out.close(); } public static void main(String[] args) throws IOException { Main task = new Main(IO_MODE.CONSOLE); task.solve(); task.out.close(); } int[] isQuad(Vector p1, Vector p2, Vector p3, Vector p4) { int[]ans = new int[4]; if (p1.length(p2) == p1.length(p3) && p1.length(p2) == p2.length(p4) && p1.is90(p2, p3) && p4.is90(p2, p3) && p2.is90(p1, p4)) { ans[0] = p1.index; ans[1] = p2.index; ans[2] = p3.index; ans[3] = p4.index; return ans; } return null; } boolean isPPPP (Vector p1, Vector p2, Vector p3, Vector p4) { if (isQuad(p1, p2, p3, p4) != null) return true; if (p1.is90(p2, p3) && p4.is90(p2, p3) && p2.is90(p1, p4)) { return true; } return false; } public void test() { ArrayList<Vector> list= new ArrayList<Vector>(); // Vector v1 = new Vector(0, 0), // A // v2 = new Vector(4, 4), // B // v3 = new Vector(4, 0), // C // v4 = new Vector(0, 4); // D Vector v1 = new Vector(1, 2), // A v2 = new Vector(2, 3), // B v3 = new Vector(3, 2), // C v4 = new Vector(2, 1); // D System.out.println(v1.length(v2)); System.out.println(v2.length(v3)); System.out.println(v3.length(v4)); System.out.println(v4.length(v1)); System.out.println(v1.is90(v2, v4)); list.add(v1); list.add(v2); list.add(v3); list.add(v4); for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { for (int k = 0; k < list.size(); k++) { for (int l = 0; l < list.size(); l++) { if (i != j && i!=k && i!=l && j!=k && j!=l && k!=l) { System.out.println(isPPPP(list.get(i), list.get(j), list.get(k), list.get(l))); } } } } } } public void solve() throws IOException { // test(); ArrayList<Vector> list = new ArrayList<Vector>(); for (int i = 0; i < 8; i++) { Vector vec = new Vector(in.nextInt(), in.nextInt()); vec.index = i; list.add(vec); } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { for (int k = 0; k < list.size(); k++) { for (int l = 0; l < list.size(); l++) { if (i != j && i!=k && i!=l && j!=k && j!=l && k!=l) { int[]tab = null; tab = isQuad(list.get(i), list.get(j), list.get(k), list.get(l)); if (tab != null) { ArrayList<Integer>qwerty = new ArrayList<Integer>(); for (int m = 0; m < 8; m++) { qwerty.add(new Integer(m)); } for (int m = 0; m < tab.length; m++) { if (qwerty.contains(tab[m])) { qwerty.remove(new Integer(tab[m])); } } for (int i2 = 0; i2 < qwerty.size(); i2++) { for (int j2 = 0; j2 < qwerty.size(); j2++) { for (int k2 = 0; k2 < qwerty.size(); k2++) { for (int l2 = 0; l2 < qwerty.size(); l2++) { if (i2 != j2 && i2!=k2 && i2!=l2 && j2!=k2 && j2!=l2 && k2!=l2) { if (isPPPP(list.get(qwerty.get(i2)), list.get(qwerty.get(j2)), list.get(qwerty.get(k2)), list.get(qwerty.get(l2)))){ System.out.println("YES"); for (int m = 0; m < tab.length; m++) { System.out.print(tab[m] + 1 + " "); } System.out.println(); for (int m = 0; m < qwerty.size(); m++) { System.out.print(qwerty.get(m) + 1 + " "); } return; } } } } } } } } } } } } System.out.println("NO"); } } class Vector { int index; double x, y; Vector() { x = 0; y = 0; } Vector(double x, double y) { this.x = x; this.y = y; } double length() { return Math.sqrt(x * x + y * y); } double length(Vector vec) { double X = Math.abs(vec.x - x), Y = Math.abs(vec.y - y); return Math.sqrt(X * X + Y * Y); } boolean is90(Vector p2, Vector p3) { double A = this.length(p2); double B = this.length(p3); double C = p2.length(p3); double res = round((A * A + B * B - C * C) / 2 * A * B); if (res == 0) return true; return false; } double round(double d) { d *= 100; d = (int)d; d /= 100; return d; } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } FastScanner(File file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } } class IO_MODE { public static final String CONSOLE = "console"; public static final String FILE = "file"; }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
51e9c2a26fc114da7d80b5e9a59feadd
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.Point; import java.io.*; import java.util.*; public class D { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); Point[] points=new Point[8]; for (int i = 0; i < points.length; i++) { String[] sp=r.readLine().split("[ ]+"); points[i]=new Point(new Integer(sp[0]),new Integer(sp[1])); } for(int i=0;i<(1<<8);i++){ if(Integer.bitCount(i)==4){ Point[] set1=new Point[4]; Point[] set2=new Point[4]; Vector<Integer> a=new Vector<Integer>(); Vector<Integer> b=new Vector<Integer>(); int x=0,y=0; for(int j=0;j<8;j++){ if(((1<<j)&i)==(1<<j)){ set1[x++]=new Point(points[j].x,points[j].y); a.add(j+1); } else{ set2[y++]=new Point(points[j].x,points[j].y); b.add(j+1); } } if(isSquare(set1)&&isRectangle(set2)){ System.out.println("YES"); print(a); print(b); System.exit(0); } else if(isSquare(set2)&&isRectangle(set1)){ System.out.println("YES"); print(b); print(a); System.exit(0); } } } System.out.println("NO"); } private static void print(Vector<Integer> a) { System.out.println(a.get(0)+" "+a.get(1)+" "+a.get(2)+" "+a.get(3)); } private static boolean isRectangle(Point[] set2) { isRect=false; s2=set2; dfsR(0,new int[]{0,1,2,3},new int[4],new boolean[4]); return isRect; } static boolean isSquare; static Point[] s1; static boolean isRect; static Point[] s2; private static boolean isSquare(Point[] set1) { isSquare=false; s1=set1; dfsS(0,new int[]{0,1,2,3},new int[4],new boolean[4]); return isSquare; } public static double len(Point a,Point b){ double dx=a.x-b.x; double dy=a.y-b.y; double side=dx*dx+dy*dy; // Sqrt side ! return side; } public static void dfsS(int i,int[] a,int[]order,boolean[] v){ if(order.length==i){ double dx=s1[order[0]].x-s1[order[1]].x; double dy=s1[order[0]].y-s1[order[1]].y; double side=dx*dx+dy*dy; // Sqrt side ! boolean can=true; for(int j=0;j<4;j++){ Point x=s1[order[j]]; Point y=s1[order[(j+1)%4]]; Point z=s1[order[(j+2)%4]]; double hypt=len(x,z); double first=len(x,y); double sec=len(y,z); if(first+sec!=hypt){ can=false; break; } } for(int j=0;j<4;j++){ double s=len(s1[order[j]],s1[order[(j+1)%4]]); if(s!=side){ can=false; break; } } if(can){ isSquare=true; } } else{ for(int j=0;j<a.length;j++){ if(v[j]) continue; order[i]=a[j]; v[j]=true; dfsS(i+1,a,order,v); v[j]=false; } } } public static void dfsR(int i,int[] a,int[]order,boolean[] v){ if(order.length==i){ double dx=s2[order[0]].x-s2[order[1]].x; double dy=s2[order[0]].y-s2[order[1]].y; double side=dx*dx+dy*dy; // Sqrt side ! boolean can=true; for(int j=0;j<4;j++){ Point x=s2[order[j]]; Point y=s2[order[(j+1)%4]]; Point z=s2[order[(j+2)%4]]; double hypt=len(x,z); double first=len(x,y); double sec=len(y,z); if(first+sec!=hypt){ can=false; break; } } double second=len(s2[order[1]],s2[order[2]]); double third=len(s2[order[2]],s2[order[3]]); double fourth=len(s2[order[3]],s2[order[0]]); if(side==third&&second==fourth){ } else{ can=false; } if(can){ isRect=true; } } else{ for(int j=0;j<a.length;j++){ if(v[j]) continue; order[i]=a[j]; v[j]=true; dfsR(i+1,a,order,v); v[j]=false; } } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
a98bf4b1ecee3d15a89bece9a65e4170
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
//package d; import java.util.*; import java.io.*; public class Main { public void run() throws Exception { Scanner in = new Scanner(System.in); int []x = new int[8]; int []y = new int[8]; for (int i = 0; i < 8; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } int a[] = new int[8]; point p[] = new point[8]; for(int i=1;i<8;i++) a[i] = i; while(a.length != 0){ for(int i=0;i<8;i++) p[i] = new point(x[a[i]], y[a[i]]); if (isSquare(p[0], p[1], p[2], p[3]) && isRect(p[4], p[5], p[6], p[7])){ System.out.println("YES"); for(int i=0;i<4;i++){ System.out.print((a[i]+1) + " "); } System.out.println(); for(int i=4;i<8;i++){ System.out.print((a[i]+1) + " "); } return; } a = nextPermutation(a); } System.out.println("NO"); } private boolean isSquare(point a, point b, point c, point d){ int dis = a.len(b); if (dis != b.len(c)) return false; if (dis != c.len(d)) return false; if (dis != d.len(a)) return false; if (!b.is90(a, c)) return false; if (!c.is90(b, d)) return false; if (!d.is90(c, a)) return false; if (!a.is90(b, d)) return false; return true; } private boolean isRect(point a, point b, point c, point d){ if (!b.is90(a, c)) return false; if (!c.is90(b, d)) return false; if (!d.is90(c, a)) return false; if (!a.is90(b, d)) return false; int dis = a.len(b); if (dis != c.len(d)) return false; dis = b.len(c); if (dis != d.len(a)) return false; return true; } int yk = 0; boolean used[]; private int[] nextPermutation(int a[]) { int k = a.length - 2; int min = Integer.MAX_VALUE; int t = 0; while (a[k] > a[k + 1]) { k--; if (k < 0) return new int[0]; } for (int i = k + 1; i < a.length; i++) if (a[k] < a[i] && min > a[i]) { min = a[i]; t = i; } a[t] = a[k]; a[k] = min; for (int i = k + 1, j = a.length - 1; i < j; i++, j--) { t = a[i]; a[i] = a[j]; a[j] = t; } return a; } public static void main(String[] args) throws Exception { new Main().run(); } } class point{ int x, y; public point(int x, int y){ this.x = x; this.y = y; } public int len(point p){ return (p.x - this.x)*(p.x - this.x) + (p.y - this.y)*(p.y - this.y); } public boolean is90(point p1, point p2){ int a1 = this.x - p1.x; int b1 = this.y - p1.y; int a2 = this.x - p2.x; int b2 = this.y - p2.y; return a1*a2 + b1*b2 == 0; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
39f2d56e78ff325e07b03d2061bf99b1
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.lang.*; import java.util.*; public class Main { public static int[] x = new int[8], y = new int[8]; public static int isRec(int[] p) { int i, j, k, l; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { for (k = 0; k < 4; k++) { for (l = 0; l < 4; l++) { if (i == j || i == k || i == k || i == l || j == k || j == l || k == l) continue; if ((x[p[k]] - x[p[i]]) * (x[p[j]] - x[p[i]]) + (y[p[k]] - y[p[i]]) * (y[p[j]] - y[p[i]]) == 0) { if (x[p[j]]- x[p[i]] == x[p[l]] - x[p[k]] && y[p[j]]- y[p[i]] == y[p[l]] - y[p[k]]) { if ((x[p[k]] - x[p[i]]) * (x[p[k]] - x[p[i]]) + (y[p[k]] - y[p[i]]) * (y[p[k]] - y[p[i]]) == (x[p[j]] - x[p[i]]) * (x[p[j]] - x[p[i]]) + (y[p[j]] - y[p[i]]) * (y[p[j]] - y[p[i]])) return 2; return 1; } } } } } } return 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int i, j; for (i = 0; i < 8; i++) { x[i] = input.nextInt(); y[i] = input.nextInt(); } int[] p1 = new int[4], p2 = new int[4]; int s1, s2; String output = "NO"; for (i = 0; i < (1 << 8); i++) { if (Integer.bitCount(i) == 4) { s1 = s2 = 0; for (j = 0; j < 8; j++) { if (((i >> j) & 1) == 1) p1[s1++] = j; else p2[s2++] = j; } int ret1 = isRec(p1); int ret2 = isRec(p2); if (ret1 == 2 && ret2 > 0) { output = "YES"; break; } } } System.out.println(output); if (output.equals("YES")) { for (i = 0; i < 4; i++) System.out.print((p1[i] + 1) + " "); System.out.println(); for (i = 0; i < 4; i++) System.out.print((p2[i] + 1) + " "); System.out.println(); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4def78baf1e52f41fac49fbc072b403e
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; public class ProblemD implements Runnable{ long[] x=new long[8]; long[] y=new long[8]; public void solve() throws IOException{ for(int i=0;i<8;i++){ int[] inp=intArr(); x[i]=(long)inp[0]; y[i]=(long)inp[1]; } int[] ind=new int[4]; int[] ind2=new int[4]; for(ind[0]=0;ind[0]<8;ind[0]++){ for(ind[1]=ind[0]+1;ind[1]<8;ind[1]++){ for(ind[2]=ind[1]+1;ind[2]<8;ind[2]++){ for(ind[3]=ind[2]+1;ind[3]<8;ind[3]++){ int ii=0; for(int i=0;i<8;i++){ boolean found=true; for(int j=0;j<4;j++){ if(ind[j]==i){ found=false; break; } } if(found){ ind2[ii]=i; ii++; } } int k1=kindOfFigure(ind); int k2=kindOfFigure(ind2); if(k1==2 && k2>0){ out.println("YES"); for(int i=0;i<4;i++){ if(i>0){ out.print(" "); } out.print(ind[i]+1); } out.println(); for(int i=0;i<4;i++){ if(i>0){ out.print(" "); } out.print(ind2[i]+1); } out.println(); return; } } } } } out.println("NO"); } private int kindOfFigure(int[] ind){ int[] ii=new int[4]; boolean[] used=new boolean[4]; ii[0]=0; used[0]=true; long[] l2=new long[4]; for(int i=1;i<4;i++){ l2[i]=dist2(ind[0],ind[i]); } ii[1]=indMin(l2, used); used[ii[1]]=true; ii[3]=indMin(l2, used); used[ii[3]]=true; ii[2]=indMin(l2, used); used[ii[2]]=true; long a1=dist2(ind[ii[0]], ind[ii[1]]); long a2=dist2(ind[ii[2]], ind[ii[3]]); long b1=dist2(ind[ii[0]], ind[ii[3]]); long b2=dist2(ind[ii[1]], ind[ii[2]]); long c1=dist2(ind[ii[0]], ind[ii[2]]); long c2=dist2(ind[ii[1]], ind[ii[3]]); int kind=0; if(a1==a2 && b1==b2 && c1==c2){ kind=1; } if(kind==1 && a1==b1){ kind=2; } return kind; } private long dist2(int ind1, int ind2){ long dx=x[ind1]-x[ind2]; long dy=y[ind1]-y[ind2]; return dx*dx+dy*dy; } private int indMin(long[] val, boolean[] used){ long min=Long.MAX_VALUE; int ind=-1; for(int i=0;i<val.length;i++){ if(val[i]<min && !used[i]){ min=val[i]; ind=i; } } return ind; } public static void main(String[] args){ new ProblemD().run(); } @Override public void run(){ // System.out.println("trying to solve"); try{ in=new BufferedReader(new InputStreamReader(stdin)); out=new PrintWriter(stdout); solve(); in.close(); out.close(); } catch (Exception ex){ ex.printStackTrace(); System.exit(1); } } BufferedReader in; PrintWriter out; int[] intArr() throws IOException { String[] arr=nextLine().split("\\s"); int[] res=new int[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Integer.parseInt(arr[i]); return res; } long[] longArr() throws IOException { String[] arr=nextLine().split("\\s"); long[] res=new long[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Long.parseLong(arr[i]); return res; } double[] doubleArr() throws IOException { String[] arr=nextLine().split("\\s"); double[] res=new double[arr.length]; for(int i=0;i<arr.length;i++) res[i]=Double.parseDouble(arr[i]); return res; } String nextLine() throws IOException { return in.readLine(); } InputStream stdin; OutputStream stdout; public ProblemD(){ stdin=System.in; stdout=System.out; } public ProblemD(InputStream stdin, OutputStream stdout){ this.stdin=stdin; this.stdout=stdout; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
397935b5d653d78741024c5c88b39a60
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class D { static int[]x,y; static int[][] comb = {{0, 1, 2, 3}, {0, 2, 1, 3}, {0, 3, 1, 2}}; public static void main(String[] args) { Scanner sc = new Scanner(System.in); x = new int[9]; y = new int[9]; for (int i = 1; i <= 8; i++) { x[i] = sc.nextInt(); y[i] = sc.nextInt(); } for (int i = 0; i < (1 << 8); i++) { String ss = Integer.toBinaryString(i); while (ss.length() != 8) { ss = "0"+ss; } int cnt = 0; for (int j = 0; j < 8; j++) { if (ss.charAt(j)=='1') { cnt++; } } if (cnt != 4) { continue; } ArrayList<Integer> squ = new ArrayList<Integer>(); ArrayList<Integer> rec = new ArrayList<Integer>(); for (int j = 0; j < 8; j++) { if (ss.charAt(j)=='1') { squ.add(j+1); } else { rec.add(j+1); } } if (squ(squ) && rec(rec)) { System.out.println("YES"); for (int t : squ) { System.out.print(t+" "); } System.out.println(); for (int t : rec) { System.out.print(t+" "); } return; } } System.out.println("NO"); } private static boolean rec(ArrayList<Integer> rec) { for (int i = 0; i < 3; i++) { int zero = rec.get(comb[i][0]); int one = rec.get(comb[i][1]); int two = rec.get(comb[i][2]); int tree = rec.get(comb[i][3]); int a = dis(zero, two); int b = dis(zero, tree); if (dis(zero, one)==dis(two, tree) && dis(one, two)==b && dis(one, tree)==a) { if ((x[tree]-x[zero])*(x[two]-x[zero])+(y[tree]-y[zero])*(y[two]-y[zero])==0) { return true; } } } return false; } private static int dis(int k1, int k2) { return (x[k1]-x[k2])*(x[k1]-x[k2])+(y[k1]-y[k2])*(y[k1]-y[k2]); } private static boolean squ(ArrayList<Integer> squ) { for (int i = 0; i < 3; i++) { int zero = squ.get(comb[i][0]); int one = squ.get(comb[i][1]); int two = squ.get(comb[i][2]); int tree = squ.get(comb[i][3]); int a = dis(zero, two); if (dis(zero, one)==dis(two, tree) && dis(zero, tree)==a && dis(one, two)==a && dis(one, tree)==a) { if ((x[tree]-x[zero])*(x[two]-x[zero])+(y[tree]-y[zero])*(y[two]-y[zero])==0) { return true; } } } return false; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
66010646de24719be0beec783736404c
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D implements Runnable { class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } } final int n = 8; boolean[] used; Point[] points; int[] p; private void Solution() throws IOException { points = new Point[n]; used = new boolean[n]; p = new int[n]; for (int i = 0; i < n; i++) { int x = nextInt(), y = nextInt(); points[i] = new Point(x, y); } rec(0); System.out.println("NO"); } void rec(int k) { for (int i = 0; i < n; i++) { if (!used[i]) { p[k] = i; used[i] = true; rec(k + 1); used[i] = false; } } if (k == n) { int[] sq = new int[n / 2]; int[] rect = new int[n / 2]; Point[] square = new Point[n / 2]; Point[] rectangle = new Point[n / 2]; for (int i = 0; i < n / 2; i++) sq[i] = p[i]; for (int i = 0; i < n / 2; i++) rect[i] = p[i + 4]; for (int i = 0; i < n / 2; i++) square[i] = points[sq[i]]; for (int i = 0; i < n / 2; i++) rectangle[i] = points[rect[i]]; if (isRectangle(rectangle) && isSquare(square)) { System.out.println("YES"); printMas(sq); printMas(rect); System.exit(0); } } return; } boolean isRectangle(Point... p) { int x1 = p[0].x, y1 = p[0].y; int x2 = p[1].x, y2 = p[1].y; int x3 = p[2].x, y3 = p[2].y; int x4 = p[3].x, y4 = p[3].y; double a1 = len(x1, y1, x2, y2); double a2 = len(x2, y2, x3, y3); double a3 = len(x3, y3, x4, y4); double a4 = len(x4, y4, x1, y1); double c1 = Math.sqrt(a1 * a1 + a2 * a2); double c2 = len(x1, y1, x3, y3); return compare(a1, a3) && compare(a2, a4) && compare(c1, c2); } boolean isSquare(Point... p) { int x1 = p[0].x, y1 = p[0].y; int x2 = p[1].x, y2 = p[1].y; int x3 = p[2].x, y3 = p[2].y; int x4 = p[3].x, y4 = p[3].y; double a1 = len(x1, y1, x2, y2); double a2 = len(x2, y2, x3, y3); double a3 = len(x3, y3, x4, y4); double a4 = len(x4, y4, x1, y1); double c1 = Math.sqrt(a1 * a1 + a2 * a2); double c2 = len(x1, y1, x3, y3); return compare(a1, a2) && compare(a1, a3) && compare(a1, a4) && compare(c1, c2); } double len(double x1, double y1, double x2, double y2) { return Math.sqrt((y1 - y2) * (y1 - y2) + (x1 - x2) * (x1 - x2)); } boolean compare(double a, double b) { final double EPS = 1e-7; return Math.abs(a - b) < EPS; } void printMas(int[] mas) { for (int i = 0; i < mas.length; i++) { System.out.print(mas[i]+1); if (i == mas.length - 1) System.out.println(); else System.out.print(" "); } } public static void main(String[] args) { new D().run(); } BufferedReader in; StringTokenizer tokenizer; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; Solution(); in.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(in.readLine()); return tokenizer.nextToken(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
ce7659de44ea2493f7388458371cece0
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Scanner; public class D97 { public static P[] p = new P[8]; private static boolean storoniravni(int a, int b, int c) { int aa = (p[a].x - p[b].x)*(p[a].x - p[b].x) + (p[a].y - p[b].y)*(p[a].y - p[b].y); int bb = (p[b].x - p[c].x)*(p[b].x - p[c].x) + (p[b].y - p[c].y)*(p[b].y - p[c].y); int cc = (p[a].x - p[c].x)*(p[a].x - p[c].x) + (p[a].y - p[c].y)*(p[a].y - p[c].y); if (aa==bb || aa==cc || bb==cc) return true; else return false; } public static class P{ public int x,y; public P(int a, int b) {x=a; y=b;} } private static boolean square(int[] pp) { if (!rect(pp)) return false; if (storoniravni(pp[0],pp[1],pp[2])) return true; return false; } private static boolean rect(int[] pp) { if (normal(pp[0],pp[1],pp[2]) && normal(pp[0],pp[1],pp[3]) && normal(pp[1],pp[2],pp[3]) && normal(pp[0],pp[2],pp[3])) return true; return false; } private static boolean normal (int a, int b, int c) { if ( (p[b].x-p[a].x)*(p[c].x-p[a].x)+(p[b].y-p[a].y)*(p[c].y-p[a].y) == 0 ) return true; if ( (p[a].x-p[b].x)*(p[c].x-p[b].x)+(p[a].y-p[b].y)*(p[c].y-p[b].y) == 0 ) return true; if ( (p[b].x-p[c].x)*(p[a].x-p[c].x)+(p[b].y-p[c].y)*(p[a].y-p[c].y) == 0 ) return true; return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int i = 0; i < 8; ++i) p[i] = new P(sc.nextInt(),sc.nextInt()); for (int i = 1; i < 256; ++i) { int ed[] = new int[8]; int zer[] = new int[8]; int k = 0, m = 0; for (int j = 0; j < 8; ++j) if ( (i & (1<<j)) == (1<<j) ) { ed[k] = j; k++; } else { zer[m] = j; m++; } if (k == 4) if (square(ed) && rect(zer)) { System.out.println("YES"); for (int j = 0; j < 4; ++j) System.out.print(ed[j]+1+" "); System.out.println(); for (int j = 0; j < 4; ++j) System.out.print(zer[j]+1+" "); System.exit(0); } } System.out.print("NO"); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
45fd840066dafabc1256715a680561b1
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.io.*; public class a { static long mod = 1000000009; static char[][] res; public static void main(String[] args) throws IOException { //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); xs = new int[8]; ys = new int[8]; String[] orders = {"0123","0132","0213","0231","0312","0321", "1023","1032","1203","1230","1302","1320", "2013","2031","2103","2130","2301","2310", "3012","3021","3102","3120","3201","3210"}; for(int i = 0; i<8; i++) { xs[i] = input.nextInt(); ys[i] = input.nextInt(); } boolean found = false; for(int i = 0; i<8; i++) for(int j = 0; j<8; j++) for(int k = 0; k<8; k++) for(int l = 0; l<8; l++) { if(i==j||i==k||i==l||j==k||j==l||k==l) continue; int[] first = {i,j,k,l}; ArrayList<Integer> secondlist = new ArrayList<Integer>(); for(int m = 0; m<8; m++) if(m != i && m != j && m != k && m != l) secondlist.add(m); int[] second = new int[4]; for(int m = 0; m<4; m++) { second[m] = secondlist.get(m); } for(int x = 0; x<24; x++) { if(found) break; for(int y = 0; y<24; y++) { int[] sortedx = new int[4]; for(int z = 0; z<4; z++) sortedx[z] = first[orders[x].charAt(z)-'0']; int[] sortedy = new int[4]; for(int z = 0; z<4; z++) sortedy[z] = second[orders[y].charAt(z)-'0']; int dist = dist(sortedx[0], sortedx[1]); if(dist != dist(sortedx[1], sortedx[2])) continue; if(dist != dist(sortedx[3], sortedx[2])) continue; if(dist != dist(sortedx[0], sortedx[3])) continue; if(dist + dist != dist(sortedx[0], sortedx[2])) continue; int dist1 = dist(sortedy[0], sortedy[1]), dist2 = dist(sortedy[2], sortedy[1]); if(dist1 != dist(sortedy[2], sortedy[3])) continue; if(dist2 != dist(sortedy[3], sortedy[0])) continue; if(dist1+dist2 != dist(sortedy[0], sortedy[2])) continue; found = true; out.println("YES"); for(int xx: sortedx) out.print((xx+1)+" "); out.println(); for(int yy: sortedy) out.print((yy+1)+" "); break; } if(found) break; } if(found) break; } if(!found) out.println("NO"); out.close(); } static int[] xs, ys; static int dist(int a, int b) { return (xs[a]-xs[b])*(xs[a]-xs[b]) + (ys[a]-ys[b])*(ys[a]-ys[b]); } static long pow(long x, long p) { if(p==0) return 1; if((p&1) > 0) { return (x*pow(x, p-1))%mod; } long sqrt = pow(x, p/2); return (sqrt*sqrt)%mod; } static long gcd(long a, long b) { if(b==0) return a; return gcd(b, a%b); } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static String nextLine() throws IOException { return reader.readLine(); } } /* Sum Interval Tree - uses O(n) space Updates and queries over a range of values in log(n) time Note: If querying all elements, use difference array instead. */ static class IT { int[] left,right, val, a, b; IT(int n) { left = new int[4*n]; right = new int[4*n]; val = new int[4*n]; a = new int[4*n]; b = new int[4*n]; init(0,0, n); } int init(int at, int l, int r) { a[at] = l; b[at] = r; if(l==r) left[at] = right [at] = -1; else { int mid = (l+r)/2; left[at] = init(2*at+1,l,mid); right[at] = init(2*at+2,mid+1,r); } return at++; } //return the sum over [x,y] int get(int x, int y) { return go(x,y, 0); } int go(int x,int y, int at) { if(at==-1) return 0; if(x <= a[at] && y>= b[at]) return val[at]; if(y<a[at] || x>b[at]) return 0; return go(x, y, left[at]) + go(x, y, right[at]); } //add v to elements x through y void add(int x, int y, int v) { go3(x, y, v, 0); } void go3(int x, int y, int v, int at) { if(at==-1) return; if(y < a[at] || x > b[at]) return; val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v; go3(x, y, v, left[at]); go3(x, y, v, right[at]); } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
ddaf6f23dbca4e6207ab04244ecda049
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.Point; import java.io.BufferedInputStream; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class RectangleAndSquare { //Round #97 - Rectangle and Square public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); Point[] points = new Point[8]; for(int i = 0; i < points.length; i++) { points[i] = new Point(sc.nextInt(), sc.nextInt()); } boolean possible = false; outer: for(int i = 0; i <= 255; i++) { String binaryStr = Integer.toString(i, 2); while(binaryStr.length() < 8) { binaryStr = "0" + binaryStr; } int oneCount = 0; for(int j = 0; j < binaryStr.length(); j++) { if(binaryStr.charAt(j) == '1') { oneCount++; } } if(oneCount == 4) { Point[] squarePoints = new Point[4]; Point[] rectanglePoints = new Point[4]; int[] squareIndices = new int[4]; int[] rectangleIndices = new int[4]; int squareIndex = 0; int rectangleIndex = 0; for(int j = 0; j < binaryStr.length(); j++) { if(binaryStr.charAt(j) == '1') { squarePoints[squareIndex] = points[j]; squareIndices[squareIndex] = j + 1; squareIndex++; } else { rectanglePoints[rectangleIndex] = points[j]; rectangleIndices[rectangleIndex] = j + 1; rectangleIndex++; } } if(isPossible(squarePoints, rectanglePoints)) { System.out.println("YES"); for(int k = 0; k < squareIndices.length - 1; k++) { System.out.print(squareIndices[k] + " "); } System.out.println(squareIndices[squareIndices.length - 1]); for(int k = 0; k < rectangleIndices.length - 1; k++) { System.out.print(rectangleIndices[k] + " "); } System.out.println(rectangleIndices[rectangleIndices.length - 1]); possible = true; break outer; } } } if(!possible) { System.out.println("NO"); } } private static boolean isPossible(Point[] squarePoints, Point[] rectanglePoints) { final int SQUARE = 0; for(int whichShape = 0; whichShape < 2; whichShape++) { Point[] pointArray; if(whichShape == SQUARE) { pointArray = squarePoints; } else { pointArray = rectanglePoints; } sortPoints(pointArray); double[] dists = new double[4]; for(int i = 0; i < 4; i++) { dists[i] = pointArray[i].distance(pointArray[(i + 1) % 4]); } if(whichShape == SQUARE) { if(!(dists[0] == dists[1] && dists[1] == dists[2] && dists[2] == dists[3])) { return false; } } else { if(!(dists[0] == dists[2] && dists[1] == dists[3])) { return false; } } double[] angles = new double[4]; for(int i = 0; i < 4; i++) { angles[i] = angleBetweenLines(pointArray[(i + 1) % 4], pointArray[i], pointArray[(i + 2) % 4]); final double EPS = 10e-6; if(!(Math.abs(Math.abs(angles[i]) - 90) < EPS || Math.abs(Math.abs(angles[i]) - 270) < EPS)) { return false; } } } return true; } /** * @return The angle in degrees between the two lines starting from commonPoint and going to each of the other two points respectively. */ private static double angleBetweenLines(Point commonPoint, Point lineOneEndPoint, Point lineTwoEndPoint) { lineOneEndPoint = new Point(lineOneEndPoint); lineOneEndPoint.translate(-commonPoint.x, -commonPoint.y); lineTwoEndPoint = new Point(lineTwoEndPoint); lineTwoEndPoint.translate(-commonPoint.x, -commonPoint.y); double angle = Math.atan2(lineTwoEndPoint.y, lineTwoEndPoint.x) - Math.atan2(lineOneEndPoint.y, lineOneEndPoint.x); return Math.toDegrees(angle); } /** * Sorts points counter-clockwise on their angle with the point with the lowest y coordinate. */ private static void sortPoints(Point[] points) { //Find the point with the lowest y coordinate (and lowest x coordinate if it's a tie) Point lowestYPoint = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); for(int i = 0; i < points.length; i++) { Point p = points[i]; if(p.y < lowestYPoint.y) { lowestYPoint = p; } else if(p.y == lowestYPoint.y && p.x < lowestYPoint.x) { lowestYPoint = p; } } final Point point0 = lowestYPoint; Comparator<Point> counterClockwiseSorter = new Comparator<Point>() { public int compare(Point point1, Point point2) { int side = sideOfLine(point2, point0, point1); if(side == 0) { if(point1.distanceSq(point0) > point2.distanceSq(point0)) { return 1; } else if(point1.distanceSq(point0) == point2.distanceSq(point0)) { return 0; } else { return -1; } } else { return -side; } } }; Arrays.sort(points, counterClockwiseSorter); } public static int sideOfLine(Point p, Point line1, Point line2) { return (line2.x - line1.x) * (p.y - line1.y) - (p.x - line1.x) * (line2.y - line1.y); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4aa1b661b94c5d7598c5eec67af15645
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
//package beta97; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { public static BufferedReader br; public static StringTokenizer inp; public static PrintWriter out; static int x[], y[]; static double eps = 1e-8; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); x = new int[8]; y = new int[8]; for(int i = 0 ; i < 8 ; i++) { inp = new StringTokenizer(br.readLine()); x[i] = nextInt(); y[i] = nextInt(); } boolean no = true; int ind[] = new int[4]; for(ind[0] = 0 ; ind[0] < 8 ; ind[0]++) { for(ind[1] = ind[0]+1 ; ind[1] < 8 ; ind[1]++) { for(ind[2] = ind[1]+1 ; ind[2] < 8 ; ind[2]++) { for(ind[3] = ind[2]+1 ; ind[3] < 8 ; ind[3]++) { if(checkSq(ind)) { int rect = 0; for(int i = 0 ; i < 4 ; i++)rect|=1<<ind[i]; int ind2[] = new int[4]; int j = 0; for(int i = 0 ; i < 8 ; i++) { if(((1<<i)&rect)==0) { ind2[j++] = i; } } if(checkRect(ind2)) { System.out.println("YES"); print(ind, ind2); no = false; ind[0] = ind[1]= ind[2] = ind[3] = 9; } } } } } } if(no)System.out.println("NO"); br.close(); out.close(); } public static boolean checkSq(int ind[]) { int ii[] = sort(ind); if(!checkRect(ind))return false; if(Math.abs(Math.sqrt((x[ii[0]] - x[ii[1]])*(x[ii[0]] - x[ii[1]]) + (y[ii[0]] - y[ii[1]])*(y[ii[0]] - y[ii[1]])) - Math.sqrt((x[ii[2]] - x[ii[1]])*(x[ii[2]] - x[ii[1]]) + (y[ii[2]] - y[ii[1]])*(y[ii[2]] - y[ii[1]]))) < eps)return true; return false; } public static boolean checkRect(int ind[]) { int ii[] = sort(ind); for(int i= 1 ; i < 4 ; i++) { if(!isStaple( x[ii[i-1]] , y[ii[i-1]], x[ii[i]], y[ii[i]], x[ii[(i+1)%4]], y[ii[(i+1)%4]])) return false; } return true; } public static boolean isStaple(int a, int b, int c , int d, int e, int f) { if(a==c && d==f || b==d&& c==e)return true; if(Math.abs((double)(b-d)*(d-f)/((a-c)*(c-e)) + 1) < eps )return true; return false; } public static int[] sort(int ind[]) { int ll=0; int ind2[] = new int[4]; for(int i = 1 ; i < 4 ;i++) { if(y[ind[i]] < y[ind[ll]]) ll = i; else if(y[ind[i]] == y[ind[ll]]) { if(x[ind[i]] < x[ind[ll]])ll = i; } } ind2[0] = ind[ll]; ll=0; for(int i = 1 ; i < 4 ;i++) { if(x[ind[i]] < x[ind[ll]]) ll = i; else if(x[ind[i]] == x[ind[ll]]) { if(y[ind[i]] > y[ind[ll]])ll = i; } } ind2[1] = ind[ll]; ll=0; for(int i = 1 ; i < 4 ;i++) { if(y[ind[i]] > y[ind[ll]]) ll = i; else if(y[ind[i]] == y[ind[ll]]) { if(x[ind[i]] > x[ind[ll]])ll = i; } } ind2[2] = ind[ll]; ll=0; for(int i = 1 ; i < 4 ;i++) { if(x[ind[i]] > x[ind[ll]]) ll = i; else if(x[ind[i]] == x[ind[ll]]) { if(y[ind[i]] < y[ind[ll]])ll = i; } } ind2[3] = ind[ll]; return ind2; } public static void print(int ind1[], int ind2[]) { System.out.println((ind1[0]+1) + " " + (ind1[1]+1) + " " + (ind1[2]+1) + " " + (ind1[3]+1)); System.out.println((ind2[0]+1) + " " + (ind2[1]+1) + " " + (ind2[2]+1) + " " + (ind2[3]+1)); } public static int nextInt(){return Integer.parseInt(inp.nextToken());} public static long nextLong(){return Long.parseLong(inp.nextToken());} public static double nextDouble(){return Double.parseDouble(inp.nextToken());} public static String next(){return inp.nextToken();} }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
731712cd2069025425389fa8d661c5b7
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class four { static int[] s; static int[] r; public static void main(String[] args) { Scanner sc = new Scanner(System.in); point[] points = new point[8]; HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < 8; i++) { int x = sc.nextInt(); int y = sc.nextInt(); points[i] = new point(x, y); map.put(x + "" + y, i); } boolean found = true; boolean[] v = new boolean[8]; Arrays.sort(points); for (int i = 0; i < 8 && found; i++) for (int j = i + 1; j < 8 && found; j++) for (int k = j + 1; k < 8 && found; k++) for (int l = k + 1; l < 8 && found; l++) { Arrays.fill(v, true); v[i] = false; v[j] = false; v[k] = false; v[l] = false; boolean check = check(v, points); if (check) { found = false; } } String ans = ""; if (!found) { ans += "YES\n"; int[] a1 = { map.get((points[s[0]].i + "" + points[s[0]].j)), map.get((points[s[1]].i + "" + points[s[1]].j)), map.get((points[s[2]].i + "" + points[s[2]].j)), map.get((points[s[3]].i + "" + points[s[3]].j)) }; Arrays.sort(a1); ans += (a1[0] + 1) + " " + (a1[1] + 1) + " " + (a1[2] + 1) + " " + (a1[3] + 1) + "\n"; int[] a2 = { map.get((points[r[0]].i + "" + points[r[0]].j)), map.get((points[r[1]].i + "" + points[r[1]].j)), map.get((points[r[2]].i + "" + points[r[2]].j)), map.get((points[r[3]].i + "" + points[r[3]].j)) }; Arrays.sort(a2); ans += (a2[0] + 1) + " " + (a2[1] + 1) + " " + (a2[2] + 1) + " " + (a2[3] + 1) + "\n"; } else { ans += "NO\n"; } System.out.print(ans); } private static boolean check(boolean[] v, point[] points) { int[] square = new int[4]; int[] rect = new int[4]; int in1 = 0; int in2 = 0; for (int i = 0; i < 8; i++) if (v[i]) square[in1++] = i; else rect[in2++] = i; boolean check1 = checksquare(square, points); boolean check2 = checkRect(rect, points); if (check1 && check2) { s = square; r = rect; return true; } else { check1 = checksquare(rect, points); check2 = checkRect(square, points); if (check1 && check2) { s = rect; r = square; return true; } } return false; } private static boolean checksquare(int[] rect, point[] points) { long d1 = calcul(points, rect[0], rect[1]); long d2 = calcul(points, rect[0], rect[2]); long d3 = calcul(points, rect[1], rect[2]); long d4 = calcul(points, rect[1], rect[3]); long d5 = calcul(points, rect[2], rect[3]); long d6 = calcul(points, rect[0], rect[3]); if (d1 == d2 && d1 == d4 && d1 == d5 && d3 == d6 && d1 + d2 == d3) { return true; } else return false; } private static boolean checkRect(int[] square, point[] points) { long d1 = calcul(points, square[0], square[1]); long d2 = calcul(points, square[0], square[2]); long d3 = calcul(points, square[1], square[2]); long d4 = calcul(points, square[1], square[3]); long d5 = calcul(points, square[2], square[3]); long d6 = calcul(points, square[0], square[3]); if (d1 == d5 && d2 == d4 && d3 == d6 && d1 + d2 == d3) { return true; }else return false; } private static long calcul(point[] points, int i, int j) { long d = (points[i].i - points[j].i) * (points[i].i - points[j].i) + (points[i].j - points[j].j) * (points[i].j - points[j].j); return d; } static class point implements Comparable<point> { int i; int j; public point(int ii, int jj) { i = ii; j = jj; } public int compareTo(point arg0) { // TODO Auto-generated method stub if (j < arg0.j) return 1; else if (j > arg0.j) return -1; else if (i < arg0.i) return 1; else return -1; } public String toString() { return "("+j+" "+i+")"; } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
4c2ee59aa2cdf06b93ca9f0f692b6d24
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.*; import java.io.*; public class C97D{ static BufferedReader br; public static void main(String args[])throws Exception{ br=new BufferedReader(new InputStreamReader(System.in)); Point p[]=new Point[8]; for(int i=0;i<8;i++){ int nm[]=toIntArray(); p[i]=new Point(nm[0],nm[1]); } boolean used[]=new boolean[8]; for(int p1=0;p1<8;p1++) for(int p2=0;p2<8;p2++) if(p1!=p2) for(int p3=0;p3<8;p3++) if(p2!=p3 && p1!=p3) for(int p4=0;p4<8;p4++) if(p1!=p4 && p2!=p4 && p3!=p4){ Arrays.fill(used, false); int a=isRect(p[p1],p[p2],p[p3],p[p4]); used[p1]=true; used[p2]=true; used[p3]=true; used[p4]=true; if(a==2){ Point t[]=new Point[4]; int c=0; for(int i=0;i<8;i++){ if(!used[i]) t[c++]=p[i]; } int b=isRect(t); if(b>0){ prln("YES"); prln((p1+1)+" "+(p2+1)+" "+(p3+1)+" "+(p4+1)); for(int i=0;i<8;i++){ if(!used[i]) pr((i+1)+" "); } prln(""); return; } } } prln("NO"); } public static int isRect(Point p1,Point p2,Point p3,Point p4){ int ret=0; int x1=p1.x; int x2=p2.x; int x3=p3.x; int x4=p4.x; int y1=p1.y; int y2=p2.y; int y3=p3.y; int y4=p4.y; x2 -= x1; x3 -= x1; x4 -= x1; y2 -= y1; y3 -= y1; y4 -= y1; if((x2 + x3 == x4 && y2 + y3 == y4 && x2 * x3 == -y2 * y3) || (x2 + x4 == x3 && y2 + y4 == y3 && x2 * x4 == -y2 * y4) || (x3 + x4 == x2 && y3 + y4 == y2 && x3 * x4 == -y3 * y4)){ if(sqr(p1,p2,p3)){ ret=2; } else ret=1; } return ret; } public static int isRect(Point p[]){ int ret=0; int x1=p[0].x; int x2=p[1].x; int x3=p[2].x; int x4=p[3].x; int y1=p[0].y; int y2=p[1].y; int y3=p[2].y; int y4=p[3].y; x2 -= x1; x3 -= x1; x4 -= x1; y2 -= y1; y3 -= y1; y4 -= y1; if((x2 + x3 == x4 && y2 + y3 == y4 && x2 * x3 == -y2 * y3) || (x2 + x4 == x3 && y2 + y4 == y3 && x2 * x4 == -y2 * y4) || (x3 + x4 == x2 && y3 + y4 == y2 && x3 * x4 == -y3 * y4)){ if(sqr(p[0],p[1],p[2])){ ret=2; } else ret=1; } return ret; } public static boolean sqr(Point p1, Point p2, Point p3){ double a=Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); double b=Math.sqrt((p2.x-p3.x)*(p2.x-p3.x)+(p2.y-p3.y)*(p2.y-p3.y)); double c=Math.sqrt((p1.x-p3.x)*(p1.x-p3.x)+(p1.y-p3.y)*(p1.y-p3.y)); return (a==b && a<c)|| (b==c && b<c) || (a==c && a<b); } /****************************************************************/ public static int[] toIntArray()throws Exception{ String str[]=br.readLine().split(" "); int k[]=new int[str.length]; for(int i=0;i<str.length;i++){ k[i]=Integer.parseInt(str[i]); } return k; } public static int toInt()throws Exception{ return Integer.parseInt(br.readLine()); } public static long[] toLongArray()throws Exception{ String str[]=br.readLine().split(" "); long k[]=new long[str.length]; for(int i=0;i<str.length;i++){ k[i]=Long.parseLong(str[i]); } return k; } public static long toLong()throws Exception{ return Long.parseLong(br.readLine()); } public static double[] toDoubleArray()throws Exception{ String str[]=br.readLine().split(" "); double k[]=new double[str.length]; for(int i=0;i<str.length;i++){ k[i]=Double.parseDouble(str[i]); } return k; } public static double toDouble()throws Exception{ return Double.parseDouble(br.readLine()); } public static String toStr()throws Exception{ return br.readLine(); } public static String[] toStrArray()throws Exception{ String str[]=br.readLine().split(" "); return str; } public static void pr(Object st){ System.out.print(st); } public static void prln(Object st){ System.out.println(st); } /****************************************************************/ } class Point{ int x; int y; public Point(int xx, int yy){ x=xx; y=yy; } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
05cbc1a8235d79e4b0e9bfc19bc03c95
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.util.Scanner; public class D { int order[] = new int[4]; private static boolean isSquare(int x[], int y[]) { String[] orders = { "0123", "0132", "0231" }; line[] lines = new line[4]; for (int i = 0; i < orders.length; i++) { lines[0] = new line(x[orders[i].charAt(0) - '0'], y[orders[i].charAt(0) - '0'], x[orders[i].charAt(1) - '0'], y[orders[i].charAt(1) - '0']); lines[1] = new line(x[orders[i].charAt(0) - '0'], y[orders[i].charAt(0) - '0'], x[orders[i].charAt(2) - '0'], y[orders[i].charAt(2) - '0']); if (lines[0].len() - lines[1].len() > 1e-9) continue; lines[2] = new line(x[orders[i].charAt(3) - '0'], y[orders[i].charAt(3) - '0'], x[orders[i].charAt(1) - '0'], y[orders[i].charAt(1) - '0']); if (lines[1].len() - lines[2].len() > 1e-9) continue; lines[3] = new line(x[orders[i].charAt(3) - '0'], y[orders[i].charAt(3) - '0'], x[orders[i].charAt(2) - '0'], y[orders[i].charAt(2) - '0']); if (lines[1].len() - lines[3].len() > 1e-9) continue; if (isperp(lines[0], lines[1]) && isperp(lines[2], lines[3])) if (lines[0].len() > 0 && lines[1].len() > 0 && lines[2].len() > 0 && lines[3].len() > 0) return true; } return false; } private static boolean isRect(int x[], int y[]) { String[] orders = { "0123", "0132", "0231" }; line[] lines = new line[4]; for (int i = 0; i < orders.length; i++) { lines[0] = new line(x[orders[i].charAt(0) - '0'], y[orders[i].charAt(0) - '0'], x[orders[i].charAt(1) - '0'], y[orders[i].charAt(1) - '0']); lines[1] = new line(x[orders[i].charAt(0) - '0'], y[orders[i].charAt(0) - '0'], x[orders[i].charAt(2) - '0'], y[orders[i].charAt(2) - '0']); lines[2] = new line(x[orders[i].charAt(3) - '0'], y[orders[i].charAt(3) - '0'], x[orders[i].charAt(1) - '0'], y[orders[i].charAt(1) - '0']); lines[3] = new line(x[orders[i].charAt(3) - '0'], y[orders[i].charAt(3) - '0'], x[orders[i].charAt(2) - '0'], y[orders[i].charAt(2) - '0']); if (isperp(lines[0], lines[1]) && isperp(lines[2], lines[3])) if (lines[0].len() > 0 && lines[1].len() > 0 && lines[2].len() > 0 && lines[3].len() > 0) return true; } return false; } public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int[] x = new int[8], y = new int[8]; for (int i = 0; i < 8; i++) { x[i] = myScanner.nextInt(); y[i] = myScanner.nextInt(); } int cnt1, cnt2; int[] squX = new int[4], squY = new int[4], rectx = new int[4], recty = new int[4]; String sq = "", rec = ""; for (int i = 0; i < 8; i++) for (int j = i + 1; j < 8; j++) for (int k = j + 1; k < 8; k++) for (int l = k + 1; l < 8; l++) { cnt1 = cnt2 = 0; sq = rec = ""; for (int ii = 0; ii < 8; ii++) if (ii == i || ii == j || ii == k | ii == l) { squX[cnt1] = x[ii]; squY[cnt1++] = y[ii]; sq += " " + (ii + 1); } else { rectx[cnt2] = x[ii]; recty[cnt2++] = y[ii]; rec += " " + (ii + 1); } if (isSquare(squX, squY) && isRect(rectx, recty)) { System.out.println("YES"); System.out.println(sq.substring(1)); System.out.println(rec.substring(1)); System.exit(0); } } System.out.println("NO"); } private static boolean isperp(line a, line b) { if (Math.abs((a.x1 - a.x2) * (b.x1 - b.x2) + (a.y1 - a.y2) * (b.y1 - b.y2)) < 1e-9) return true; return false; } static class line { int x1, y1, x2, y2; public line(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } private double len() { return Math.hypot(x1 - x2, y1 - y2); } @Override public String toString() { return x1 + " " + y1 + " " + x2 + " " + y2; } } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
19ea38df6ccbcaf9242c56779396dc5c
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.awt.Point; import java.util.Scanner; public class D { static Point[] P = new Point[8]; static int[] A = new int[8]; public static int norm(Point x) { return x.x * x.x + x.y * x.y; } public static int dot(Point x, Point y) { return x.x * y.x + x.y * y.y; } public static boolean checkSquare() { for (int i = 0; i < 4; i++) for (int j = i + 1; j < 4; j++) if (P[A[i]].x == P[A[j]].x && P[A[i]].y == P[A[j]].y) return false; Point[] V = new Point[4]; for (int i = 0; i < 4; i++) { V[i] = new Point(P[A[i]].x - P[A[(i + 1) % 4]].x, P[A[i]].y - P[A[(i + 1) % 4]].y); } for (int i = 0; i < 4; i++) if (dot(V[i], V[(i + 1) % 4]) != 0) { return false; } for (int i = 0; i < 4; i++) if (norm(V[i]) != norm(V[0])) return false; return true; } public static boolean checkRectangle() { for (int i = 4; i < 8; i++) for (int j = i + 1; j < 8; j++) if (P[A[i]].x == P[A[j]].x && P[A[i]].y == P[A[j]].y) return false; Point[] V = new Point[4]; for (int i = 4; i < 8; i++) { V[i % 4] = new Point(P[A[i]].x - P[A[(i + 1) % 4 + 4]].x, P[A[i]].y - P[A[(i + 1) % 4 + 4]].y); } for (int i = 0; i < 4; i++) if (dot(V[i], V[(i + 1) % 4]) != 0) { return false; } return true; } public static void rec(int index) { if (index == 8) { if (checkSquare() && checkRectangle()) { System.out.println("YES"); for (int i = 0; i < 4; i++) System.out.print(A[i] + 1 + " "); System.out.println(); for (int i = 4; i < 8; i++) System.out.print(A[i] + 1 + " "); System.out.println(); System.exit(0); } } for (int i = index; i < 8; i++) { int temp = A[i]; A[i] = A[index]; A[index] = temp; rec(index + 1); temp = A[i]; A[i] = A[index]; A[index] = temp; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); for (int i = 0; i < 8; i++) { P[i] = new Point(in.nextInt(), in.nextInt()); A[i] = i; } rec(0); System.out.println("NO"); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
a5198f65c958050af74813cba589c049
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import java.io.*; import java.util.*; public class TaskB { BufferedReader br; PrintWriter out; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return "-1"; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } int[] x = new int[8]; int[] y = new int[8]; long dist(int x1, int y1, int x2, int y2) { return ((long) (x1) - (long) (x2)) * ((long) (x1) - (long) (x2)) + ((long) (y1) - (long) (y2)) * ((long) (y1) - (long) (y2)); } boolean perp(int x1, int y1, int x2, int y2) { return x1 * x2 + y1 * y2 == 0; } boolean ok1(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { if (!perp(x1 - x2, y1 - y2, x3 - x2, y3 - y2) || !perp(x2 - x3, y2 - y3, x4 - x3, y4 - y3) || !perp(x3 - x4, y3 - y4, x1 - x4, y1 - y4) || !perp(x4 - x1, y4 - y1, x2 - x1, y2 - y1)) { return false; } return true; } boolean ok2(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { if (!ok1(x1, y1, x2, y2, x3, y3, x4, y4)) { return false; } long x = dist(x1, y1, x2, y2); if (x != dist(x2, y2, x3, y3) || x != dist(x3, y3, x4, y4) || x != dist(x4, y4, x1, y1)) { return false; } return true; } void solve() throws IOException { for (int i = 0; i < 8; i++) { x[i] = nextInt(); y[i] = nextInt(); } boolean[] used = new boolean[8]; for (int i1 = 0; i1 < 8; i1++) { used[i1] = true; for (int i2 = 0; i2 < 8; i2++) { if (used[i2]) { continue; } used[i2] = true; for (int i3 = 0; i3 < 8; i3++) { if (used[i3]) { continue; } used[i3] = true; for (int i4 = 0; i4 < 8; i4++) { if (used[i4]) { continue; } used[i4] = true; for (int i5 = 0; i5 < 8; i5++) { if (used[i5]) { continue; } used[i5] = true; for (int i6 = 0; i6 < 8; i6++) { if (used[i6]) { continue; } used[i6] = true; for (int i7 = 0; i7 < 8; i7++) { if (used[i7]) { continue; } used[i7] = true; for (int i8 = 0; i8 < 8; i8++) { if (used[i8]) { continue; } if (ok2(x[i1], y[i1], x[i2], y[i2], x[i3], y[i3], x[i4], y[i4]) && ok1(x[i5], y[i5], x[i6], y[i6], x[i7], y[i7], x[i8], y[i8])) { out.println("YES"); out.print(i1 + 1); out.print(' '); out.print(i2 + 1); out.print(' '); out.print(i3 + 1); out.print(' '); out.print(i4 + 1); out.println(); out.print(i5 + 1); out.print(' '); out.print(i6 + 1); out.print(' '); out.print(i7 + 1); out.print(' '); out.print(i8 + 1); return; } } used[i7] = false; } used[i6] = false; } used[i5] = false; } used[i4] = false; } used[i3] = false; } used[i2] = false; } used[i1] = false; } out.print("NO"); } void run() throws IOException { // br = new BufferedReader(new FileReader("taskb.in")); // out = new PrintWriter("taskb.out"); // br = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); br.close(); out.close(); } public static void main(String[] args) throws IOException { // Locale.setDefault(Locale.US); new TaskB().run(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output
PASSED
cfb1580fdd8d052caf84579cf10f2367
train_000.jsonl
1323443100
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
256 megabytes
import static java.lang.Math.*; import java.util.*; import java.io.*; public class D { class P { int x,y; public P(int xx, int yy) { x=xx; y=yy; } public String toString() { return x + "," + y; } } int[][] perm = {{1,2,3,4,}, {1,2,4,3,}, {1,3,2,4,}, {1,3,4,2,}, {1,4,2,3,}, {1,4,3,2,}, {2,1,3,4,}, {2,1,4,3,}, {2,3,1,4,}, {2,3,4,1,}, {2,4,1,3,}, {2,4,3,1,}, {3,1,2,4,}, {3,1,4,2,}, {3,2,1,4,}, {3,2,4,1,}, {3,4,1,2,}, {3,4,2,1,}, {4,1,2,3,}, {4,1,3,2,}, {4,2,1,3,}, {4,2,3,1,}, {4,3,1,2,}, {4,3,2,1,},}; public void solve() throws Exception { P p[] = new P[8]; for (int i=0; i<8; ++i) p[i] = new P(nextInt(), nextInt()); for (int i=0; i<256; ++i) if (Integer.bitCount(i)==4) { P[] p1 = new P[4], p2 = new P[4]; int i1 = 0, i2 = 0; for (int j=0; j<8; ++j) if (hasBit(i, j)) p1[i1++] = p[j]; else p2[i2++] = p[j]; P[][] p1p = new P[24][4]; P[][] p2p = new P[24][4]; for (int j=0; j<24; ++j) { for (int k=0; k<4; ++k) p1p[j][k] = p1[perm[j][k]-1]; for (int k=0; k<4; ++k) p2p[j][k] = p2[perm[j][k]-1]; } for (int j=0; j<24; ++j) next: for (int k=0; k<24; ++k) { int d = dist(p1p[j][0], p1p[j][3]); for (int m=0; m<3; ++m) if (d!=dist(p1p[j][m], p1p[j][m+1])) continue next; if (dist(p2p[k][0], p2p[k][1]) != dist(p2p[k][2], p2p[k][3]) || dist(p2p[k][1], p2p[k][2]) != dist(p2p[k][0], p2p[k][3])) continue next; for (int m=1; m<=4; ++m) if (!perp(p1p[j][m%4],p1p[j][(m+1)%4],p1p[j][(m-1)%4])) continue next; for (int m=1; m<=4; ++m) if (!perp(p2p[k][m%4],p2p[k][(m+1)%4],p2p[k][(m-1)%4])) continue next; println("YES"); for (int m=0; m<8; ++m) if (hasBit(i, m)) print((m+1)+" "); println(); for (int m=0; m<8; ++m) if (!hasBit(i, m)) print((m+1)+" "); return; } } println("NO"); } int dist(P p1, P p2) { return (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y); } boolean perp(P s, P p1, P p2) { return ((p1.x-s.x)*(p2.x-s.x) + (p1.y-s.y)*(p2.y-s.y)) == 0 ? true:false; } //////////////////////////////////////////////////////////////////////////// boolean showDebug = true; static boolean useFiles = false; static String inFile = "input.txt"; static String outFile = "output.txt"; double EPS = 1e-7; int INF = Integer.MAX_VALUE; long INFL = Long.MAX_VALUE; double INFD = Double.MAX_VALUE; int absPos(int num) { return num<0 ? 0:num; } long absPos(long num) { return num<0 ? 0:num; } double absPos(double num) { return num<0 ? 0:num; } int min(int... nums) { int r = INF; for (int i: nums) if (i<r) r=i; return r; } int max(int... nums) { int r = -INF; for (int i: nums) if (i>r) r=i; return r; } long minL(long... nums) { long r = INFL; for (long i: nums) if (i<r) r=i; return r; } long maxL(long... nums) { long r = -INFL; for (long i: nums) if (i>r) r=i; return r; } double minD(double... nums) { double r = INFD; for (double i: nums) if (i<r) r=i; return r; } double maxD(double... nums) { double r = -INFD; for (double i: nums) if (i>r) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<<pos))>0; } long binpow(long a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } String stringn(String s, int n) { if (n<1) return ""; StringBuilder sb = new StringBuilder(s.length()*n); for (int i=0; i<n; ++i) sb.append(s); return sb.toString(); } String str(Object o) { return o.toString(); } long timer = System.currentTimeMillis(); void startTimer() { timer = System.currentTimeMillis(); } void stopTimer() { System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0); } static class InputReader { private byte[] buf; private int bufPos = 0, bufLim = -1; private InputStream stream; public InputReader(InputStream stream, int size) { buf = new byte[size]; this.stream = stream; } private void fillBuf() throws IOException { bufLim = stream.read(buf); bufPos = 0; } char read() throws IOException { if (bufPos>=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos<bufLim; } } static InputReader inputReader; static BufferedWriter outputWriter; char nextChar() throws IOException { return inputReader.read(); } char nextNonWhitespaceChar() throws IOException { char c = inputReader.read(); while (c<=' ') c=inputReader.read(); return c; } String nextWord() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c>' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i<size; ++i) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i=0; i<size; ++i) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i=0; i<size; ++i) arr[i] = nextDouble(); return arr; } String[] nextArrS(int size) throws NumberFormatException, IOException { String[] arr = new String[size]; for (int i=0; i<size; ++i) arr[i] = nextWord(); return arr; } char[] nextArrCh(int size) throws IOException { char[] arr = new char[size]; for (int i=0; i<size; ++i) arr[i] = nextNonWhitespaceChar(); return arr; } char[][] nextArrCh(int rows, int columns) throws IOException { char[][] arr = new char[rows][columns]; for (int i=0; i<rows; ++i) for (int j=0; j<columns; ++j) arr[i][j] = nextNonWhitespaceChar(); return arr; } char[][] nextArrChBorders(int rows, int columns, char border) throws IOException { char[][] arr = new char[rows+2][columns+2]; for (int i=1; i<=rows; ++i) for (int j=1; j<=columns; ++j) arr[i][j] = nextNonWhitespaceChar(); for (int i=0; i<columns+2; ++i) { arr[0][i] = border; arr[rows+1][i] = border; } for (int i=0; i<rows+2; ++i) { arr[i][0] = border; arr[i][columns+1] = border; } return arr; } void printf(String format, Object... args) throws IOException { outputWriter.write(String.format(format, args)); } void print(Object o) throws IOException { outputWriter.write(o.toString()); } void println(Object o) throws IOException { outputWriter.write(o.toString()); outputWriter.newLine(); } void print(Object... o) throws IOException { for (int i=0; i<o.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(o[i].toString()); } } void println(Object... o) throws IOException { print(o); outputWriter.newLine(); } void printn(Object o, int n) throws IOException { String s = o.toString(); for (int i=0; i<n; ++i) { outputWriter.write(s); if (i!=n-1) outputWriter.write(' '); } } void printnln(Object o, int n) throws IOException { printn(o, n); outputWriter.newLine(); } void printArr(int[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Integer.toString(arr[i])); } } void printArr(long[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Long.toString(arr[i])); } } void printArr(double[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Double.toString(arr[i])); } } void printArr(String[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(arr[i]); } } void printArr(char[] arr) throws IOException { for (char c: arr) outputWriter.write(c); } void printlnArr(int[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(long[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(double[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(String[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(char[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void halt(Object... o) throws IOException { if (o.length!=0) println(o); outputWriter.flush(); outputWriter.close(); System.exit(0); } void debug(Object... o) { if (showDebug) System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); if (!useFiles) { inputReader = new InputReader(System.in, 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16); } else { inputReader = new InputReader(new FileInputStream(new File(inFile)), 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outFile))), 1<<16); } new D().solve(); outputWriter.flush(); outputWriter.close(); } }
Java
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Java 6
standard input
[ "implementation", "geometry", "brute force" ]
a36fb51b1ebb3552308e578477bdce8f
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
1,600
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
standard output