exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
50cc941220ef5a81e6521bbe81097ee2
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: <hostname> — server name (consists of words and maybe some dots separating them), /<path> — optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.
256 megabytes
import java.io.*; import java.util.*; public class C { FastScanner in; PrintWriter out; class Host { String hostName; TreeSet<String> paths; String concatenated; public Host(String hostName) { this.hostName = hostName; paths = new TreeSet<>(); } void concat() { StringBuilder sb = new StringBuilder(); for (String path : paths) { sb.append(path).append("$"); } this.concatenated = sb.toString(); } } void solve() { int n = in.nextInt(); String[] strings = new String[n]; Map<String, Host> hosts = new TreeMap<>(); for (int i = 0; i < n; i++) { strings[i] = in.next().substring(7); int slashPos = strings[i].indexOf('/'); if (slashPos == -1) { slashPos = strings[i].length(); } String hostName = strings[i].substring(0, slashPos); if (!hosts.containsKey(hostName)) { hosts.put(hostName, new Host(hostName)); } hosts.get(hostName).paths.add(strings[i].substring(slashPos)); } List<Host> allHosts = new ArrayList<>(hosts.values()); for (Host host : allHosts) { host.concat(); } Comparator<Host> comp = (o1, o2) -> o1.concatenated.compareTo(o2.concatenated); Collections.sort(allHosts, comp); List<String> output = new ArrayList<>(); for (int i = 0; i < allHosts.size(); ) { int j = i; while (j < allHosts.size() && comp.compare(allHosts.get(i), allHosts.get(j)) == 0) { j++; } if (j - i > 1) { StringBuilder line = new StringBuilder(); for (int t = i; t < j; t++) { line.append("http://").append(allHosts.get(t).hostName); if (t + 1 < j) { line.append(' '); } } output.add(line.toString()); } i = j; } out.println(output.size()); for (String line : output) { out.println(line); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new C().runIO(); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
19fb83f6197f162d900d74ab9da6e3fc
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.util.*; public class HostnameAliases { public static void main(String[] args) { Map<String, Set<String>> domains = readInput(); Map<Set<String>, Set<String>> hosts = getSameServerGroups(domains); printAnswer(hosts); } private static void printAnswer(Map<Set<String>, Set<String>> hosts) { List<Set<String>> groupServers = new ArrayList<>(); for (Set<String> host : hosts.keySet()) { Set<String> domains = hosts.get(host); if (domains.size() > 1) { groupServers.add(domains); } } System.out.println(groupServers.size()); for (Set<String> groupServer : groupServers) { for (String server : groupServer) { System.out.print("http://" + server + " "); } System.out.println(); } } private static Map<Set<String>, Set<String>> getSameServerGroups(Map<String, Set<String>> domains) { Map<Set<String>, Set<String>> hosts = new HashMap<>(); for (String domain : domains.keySet()) { Set<String> domainHosts = domains.get(domain); Set<String> hostDomains = hosts.get(domainHosts); if (hostDomains == null) { hostDomains = new HashSet<>(); hostDomains.add(domain); hosts.put(domainHosts, hostDomains); } else { hostDomains.add(domain); } } return hosts; } private static void printMap(Map<String, Set<String>> map) { for (String key : map.keySet()) { System.out.print(key + ": "); for (String value : map.get(key)) { System.out.print(value + ", "); } System.out.println(); } } private static Map<String, Set<String>> readInput() { Map<String, Set<String>> domains = new HashMap<>(); Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < n; i++) { String line = scanner.nextLine(); String domain = ""; String host = ""; String withoutHttp = line.substring(7); int slashIndex = withoutHttp.indexOf('/'); if (slashIndex == -1) { domain = withoutHttp; } else { domain = withoutHttp.substring(0, slashIndex); host = withoutHttp.substring(slashIndex); } if (!domains.containsKey(domain)) { domains.put(domain, new HashSet<>()); } domains.get(domain).add(host); } return domains; } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
837f941b400abf21b29ea95a862da296
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
/*- * Codeforces problem : * http://codeforces.com/problemset/problem/644/C * * Determine the groups of server names that correspond * to one website. * Ignore groups consisting of the only server name. * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; /** * @author Karthik Venkataraman * @email kafy83@gmail.com */ public class FastHostnameAliases { static class InputReader { private static final int inputkb = 1024; private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), inputkb); } private String readNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException ex) { throw new IllegalStateException(ex); } } return tokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(readNext()); } } public static void main(String... args) { InputReader sc = new InputReader(System.in); int n = sc.nextInt(); Map<String, Set<String>> url = new HashMap<>(); Map<Set<String>, List<String>> pathToServer = new HashMap<>(); for (int i = 0; i < n; i++) { String x = sc.readNext().substring(7); String server = x.indexOf('/') == -1 ? x.substring(0, x.length()) : x.substring(0, x.indexOf('/')); String path = x.indexOf('/') == -1 ? "-1" : x.substring(x.indexOf('/')); if (!url.containsKey(server)) { url.put(server, new HashSet<>()); } url.get(server).add(path); } for (Entry<String, Set<String>> k : url.entrySet()) { Set<String> paths = k.getValue(); if (!pathToServer.containsKey(paths)) { pathToServer.put(paths, new ArrayList<>()); } pathToServer.get(paths).add(k.getKey()); } List<String>[] output = new ArrayList[pathToServer.size()]; int ptr = 0; for (List<String> servers : pathToServer.values()) { if (servers.size() > 1) { output[ptr++] = servers; } } System.out.println(ptr); for (int i = 0; i < ptr; i++) { for (int j = 0; j < output[i].size(); j++) { System.out.print("http://" + output[i].get(j) + " "); } System.out.println(); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
40398eb5c1249b83ea2e443a83db903d
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; 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); TaskC solver = new TaskC(); solver.solve(in, out); out.close(); } } class TaskC { public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); TreeMap<String, TreeSet<Pair>> hosts = new TreeMap<String, TreeSet<Pair>>(); for(int i = 0; i < n; i++) { String s = in.nextLine().substring(7); String host = s.substring(0, s.indexOf('/') == -1 ? s.length() : s.indexOf('/')); String path = s.indexOf('/') == -1 ? "" : s.substring(s.indexOf('/')); if(hosts.containsKey(host)) { hosts.get(host).add(getHash(path)); }else { hosts.put(host, new TreeSet<Pair>()); hosts.get(host).add(getHash(path)); } } TreeMap<String, ArrayList<String>> groups = new TreeMap<String, ArrayList<String>>(); for(String host : hosts.keySet()) { StringBuilder str = new StringBuilder(""); for(Pair p : hosts.get(host)) { str.append("("+p.hash1+";"+p.hash2+")"); } String s = str.toString(); if(groups.containsKey(s)) { groups.get(s).add(host); }else { groups.put(s, new ArrayList<String>()); groups.get(s).add(host); } } ArrayList<Integer> cntAns = new ArrayList<Integer>(); ArrayList<String> ans = new ArrayList<String>(); int cnt = 0; for(String group : groups.keySet()) { if(groups.get(group).size() > 1) { cnt++; int cntA = 0; for(String host : groups.get(group)) { ans.add(host); cntA++; } cntAns.add(cntA); } } out.writeln(cnt); for(int k=0, i = 0; i < ans.size(); k++) { int j; for(j = i; j < i + cntAns.get(k); j++) { out.write("http://"+ans.get(j)+ " "); } out.writeln(); i = j; } } Pair getHash(String s) { hash1 = hash2 = 0; p1 = p2 = 1; for(int i = 0; i < s.length(); i++) { hash1 = (hash1 + s.charAt(i) * p1) % MOD1; p1 = (p1 * pow1 ) % MOD1; hash2 = (hash2 + s.charAt(i) * p2) % MOD2; p2 = (p2 * pow2) % MOD2; } return new Pair(hash1, hash2); } long hash1 = 0, hash2 = 0; long p1 = 1, p2 = 1; long pow1 = 17, pow2 = 29; long MOD1 = 1000000007, MOD2 = 1000000009; } class Pair implements Comparable<Pair>{ public Pair(long hash1, long hash2) { this.hash1 = hash1; this.hash2 = hash2; } public int compareTo(Pair p){ return hash1 == p.hash1 ? (int)(hash2 - p.hash2) : (int)(hash1 - p.hash1); } long hash1, hash2; } class InputReader { public InputReader(InputStream inputStream) { tokenizer = null; reader = new BufferedReader(new InputStreamReader(inputStream)); } 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 String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } StringTokenizer tokenizer; BufferedReader reader; } class OutputWriter { public OutputWriter(OutputStream outputStream) { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( outputStream))); } public void write(Object... o) { for (Object x : o) out.print(x); } public void writeln(Object... o) { write(o); out.println(); } public void close() { out.close(); } PrintWriter out; }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
9ab8a21ac4bcedf2f35bb83148b45791
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; public class c { public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int N = scan.nextInt(); String[] host = new String[N], path = new String[N]; HashMap<String, TreeSet<String>> hostMap = new HashMap<>(); for(int i=0;i<N;i++){ String temp = scan.next().substring(7); int idx = temp.indexOf('/'); idx = (idx<0)?temp.length():idx; String h1 = temp.substring(0, idx); String h2 = "~!@#$%^*("; if(h1.length()!=temp.length())h2 = temp.substring(idx+1); host[i]=h1; path[i]=h2; } for(int i = 0; i < N; i++){ if(!hostMap.containsKey(host[i])){ hostMap.put(host[i], new TreeSet<String>()); } hostMap.get(host[i]).add(path[i]); } System.gc(); HashMap<TreeSet<String>, HashSet<String>> solution = new HashMap<>(); for(String s : hostMap.keySet()){ if(!solution.containsKey(hostMap.get(s))){ solution.put(hostMap.get(s), new HashSet<String>()); } solution.get(hostMap.get(s)).add(s); } int sizeDec = 0; for(TreeSet<String> b : solution.keySet())if(solution.get(b).size()==1)sizeDec++; out.println(solution.keySet().size()-sizeDec); for(TreeSet<String> b : solution.keySet()){ if(solution.get(b).size()==1)continue; for(String s : solution.get(b)){ out.print("http://"+s+" "); }out.println(); } out.close(); } private 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()); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
9b270ec2d733aff52f214db53f56a27c
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.util.*; import java.util.stream.Collectors; public class HostnameAliases { public static void main(String[] args) { final Scanner s = new Scanner(System.in); final int lines = s.nextInt(); s.nextLine(); // hostname -> paths final Map<String, Set<String>> hostToPath = new HashMap<>(lines / 2); for (int i = 0; i < lines; i++) { final String line = s.nextLine(); int indexOfSlash = line.indexOf('/', 7); if (indexOfSlash == -1) { // no path indexOfSlash = line.length(); } final String hostname = line.substring(0, indexOfSlash); Set<String> paths = hostToPath.get(hostname); if (paths == null) { paths = new HashSet<>(); hostToPath.put(hostname, paths); } paths.add(line.substring(indexOfSlash)); } // paths -> hostnames final Map<Set<String>, Set<String>> pathsToHost = new HashMap<>(lines / 4); for (final Map.Entry<String, Set<String>> entry : hostToPath.entrySet()) { final Set<String> paths = entry.getValue(); Set<String> hosts = pathsToHost.get(paths); if (hosts == null) { hosts = new HashSet<>(); pathsToHost.put(paths, hosts); } hosts.add(entry.getKey()); } // remove hosts with no matches final List<Map.Entry<Set<String>, Set<String>>> out = pathsToHost.entrySet() .stream() .filter(e -> e.getValue().size() > 1) .collect(Collectors.toList()); // output System.out.println(out.size()); for (Map.Entry<Set<String>, Set<String>> hosts : out) { for (Iterator<String> iterator = hosts.getValue().iterator(); iterator.hasNext(); ) { String host = iterator.next(); System.out.print(host); if (iterator.hasNext()) { System.out.print(" "); } } System.out.println(); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
77a3517fb3c4eb7a90c759701b12b54d
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; import java.util.Map; import java.io.IOException; import java.util.HashMap; import java.util.InputMismatchException; import java.io.PrintWriter; import java.util.TreeSet; import java.util.Map.Entry; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Artem Gilmudinov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); URI[] uris = new URI[n]; for (int i = 0; i < n; i++) { String sub = in.readLine().substring(7); int slash = sub.indexOf('/'); String domain, path; domain = path = ""; if (slash != -1) { domain = sub.substring(0, slash); path = sub.substring(slash, sub.length()); } else { domain = sub; } path += "*"; uris[i] = new URI(domain, path); } HashMap<String, TreeSet<String>> map = new HashMap<>(); for (URI uri : uris) { if (uri == null) { continue; } TreeSet<String> paths = map.get(uri.domain); if (paths == null) { paths = new TreeSet<>(); } paths.add(uri.path); map.put(uri.domain, paths); } ArrayList<Site> sites = new ArrayList<>(); for (Map.Entry<String, TreeSet<String>> entry : map.entrySet()) { TreeSet<String> paths = entry.getValue(); StringBuilder sb = new StringBuilder(); for (String path : paths) { sb.append(path); } sites.add(new Site(entry.getKey(), sb.toString())); } HashMap<String, ArrayList<Integer>> mergeMap = new HashMap<>(); for (int i = 0; i < sites.size(); i++) { Site site = sites.get(i); ArrayList<Integer> list = mergeMap.get(site.paths); if (list == null) { list = new ArrayList<>(); } list.add(i); mergeMap.put(site.paths, list); } int cnt = 0; for (Map.Entry<String, ArrayList<Integer>> entry : mergeMap.entrySet()) { if (entry.getValue().size() != 1) { ++cnt; } } out.println(cnt); for (Map.Entry<String, ArrayList<Integer>> entry : mergeMap.entrySet()) { if (entry.getValue().size() != 1) { for (Integer v : entry.getValue()) { out.print("http://" + sites.get(v).domain + " "); } out.println(); } } } class URI { String domain; String path; public URI(String domain, String path) { this.domain = domain; this.path = path; } public String toString() { return domain + " " + path; } } class Site { String domain; String paths; public Site(String domain, String paths) { this.domain = domain; this.paths = paths; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
5ecf146fe9ff38e5808d6042f53209e8
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class C_CROC2016_Qual { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); String[] data = new String[n]; HashMap<String, TreeSet<String>> map = new HashMap(); for (int i = 0; i < n; i++) { data[i] = in.next().substring(7); int index = data[i].indexOf("/"); String path = ""; if (index >= 0) { path = data[i].substring(index); data[i] = data[i].substring(0, index); } if(!map.containsKey(data[i])){ map.put(data[i], new TreeSet()); } map.get(data[i]).add(path); } HashMap<TreeSet<String>, ArrayList<String>> result = new HashMap(); for(String key : map.keySet()){ TreeSet<String> tmp = map.get(key); if(!result.containsKey(tmp)){ result.put(tmp, new ArrayList()); } result.get(tmp).add(key); } StringBuilder builder = new StringBuilder(); String prefix = "http://"; int re = 0; for(ArrayList<String> val : result.values()){ if(val.size() > 1){ re++; for(String tmp : val){ builder.append(prefix).append(tmp).append(" "); } builder.append("\n"); } } out.println(re); out.println(builder.toString()); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
261449c0a5dd246c94abd1c37fdd02bd
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { public static void main(String[] args) { MyScanner scanner = new MyScanner(); int n = scanner.nextInt(); String[] urls = new String[n]; for(int i=0;i<n;++i){ urls[i] = scanner.next().substring(7); } Map<String,TreeSet<String>> urlMap = new HashMap<>(); for(int i=0;i<n;++i){ int slashIndex = urls[i].indexOf('/'); String domain = urls[i]; String request = ""; if(slashIndex > -1){ domain = urls[i].substring(0,slashIndex); request = urls[i].substring(slashIndex); } if(!urlMap.containsKey(domain)){ urlMap.put(domain, new TreeSet<>()); } urlMap.get(domain).add(request); } Map<Long,Set<String>> hashedMap = new HashMap<>(); for(String domain:urlMap.keySet()){ long hash = calculateHash(domain,urlMap.get(domain)); if(!hashedMap.containsKey(hash)){ hashedMap.put(hash, new TreeSet<>()); } hashedMap.get(hash).add(domain); } List<Set<String>> result = new ArrayList<>(); for(long key:hashedMap.keySet()){ Set<String> domains = hashedMap.get(key); while(domains.size()>0){ String domain = domains.iterator().next(); domains.remove(domain); Set<String> group = new HashSet<>(); group.add(domain); Iterator<String> other = domains.iterator(); while(other.hasNext()){ String next = other.next(); if(equals(urlMap.get(domain),urlMap.get(next))){ other.remove(); group.add(next); } } if(group.size()>1){ result.add(group); } } } out.println(result.size()); out.flush(); for(Set<String> group:result){ for(String res:group){ out.print("http://"+res+" "); } out.println(); } out.flush(); out.close(); } private static boolean equals(TreeSet<String> strings, TreeSet<String> strings1) { if(strings.size()!=strings1.size()){ return false; } for(String st:strings){ if(!strings1.contains(st)){ return false; } } return true; } private static long calculateHash(String domain, TreeSet<String> strings) { long hash = 0; for(String req:strings){ long hashCode = req.hashCode(); hash+= 31*hash + hashCode; } return hash; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out = new PrintWriter(System.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
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
062bcb57c615aecd2e6e67710b6259f1
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; public class Main { private NotMyScanner in; private PrintWriter out; // private Timer timer = new Timer(); private String[] split(String cur) { String[] res = new String[2]; int pos = -1; for (int i = 7; i < cur.length(); i++) { if (cur.charAt(i) == '/') { pos = i; break; } } if (pos == -1) { res[0] = cur; res[1] = ""; } else { res[0] = cur.substring(0, pos); res[1] = cur.substring(pos); } return res; } /* private void getTest() throws IOException { FileWriter writer = new FileWriter("test.txt"); writer.write("100000\n"); Random random = new Random(); for (int i = 0; i < 100000; i++) { writer.write("http://"); writer.write("" + random.nextInt()); writer.write("/"); writer.write("" + random.nextInt()); writer.write("\n"); } writer.close(); } */ private void solve() throws IOException { // timer.start(); int n = in.nextInt(); Map<String, Integer> domainToId = new HashMap<>(); String[] domains = new String[100_000]; Map<String, Integer> pathToId = new HashMap<>(); Set<Integer>[] paths = new Set[100_000]; int domainIds = 0, pathIds = 0; while (n-- > 0) { String[] cur = split(in.next()); Integer domainId = domainToId.get(cur[0]); if (domainId == null) { domainId = domainIds++; domainToId.put(cur[0], domainId); domains[domainId] = cur[0]; } Integer pathId = pathToId.get(cur[1]); if (pathId == null) { pathId = pathIds++; pathToId.put(cur[1], pathId); paths[pathId] = new TreeSet<>(); } paths[pathId].add(domainId); } int[] group = new int[domainIds]; int groups = 1; for (int i = 0; i < pathIds; i++) { Map<Integer, Integer> oldToNewGroup = new HashMap<>(); for (int domainId : paths[i]) { Integer newGroup = oldToNewGroup.get(group[domainId]); if (newGroup == null) { newGroup = groups++; oldToNewGroup.put(group[domainId], newGroup); } group[domainId] = newGroup; } } ArrayList<Integer>[] groupContent = new ArrayList[groups]; for (int i = 0; i < groups; i++) { groupContent[i] = new ArrayList<>(); } for (int i = 0; i < domainIds; i++) { groupContent[group[i]].add(i); } int ans = 0; for (ArrayList<Integer> content : groupContent) { if (content.size() > 1) { ans++; } } out.println(ans); for (ArrayList<Integer> content : groupContent) { if (content.size() > 1) { for (int e : content) { out.print(domains[e] + " "); } out.println(); } } // timer.stop(); } private void run() throws IOException { // getTest(); // in = new NotMyScanner("out.txt"); in = new NotMyScanner(); out = new PrintWriter(System.out, true); solve(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } } class NotMyScanner { private final BufferedReader br; private StringTokenizer st; private String last; public NotMyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public NotMyScanner(String path) throws IOException { br = new BufferedReader(new FileReader(path)); } public NotMyScanner(String path, String decoder) throws IOException { br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(); } String nextLine() throws IOException { st = null; return (last == null) ? br.readLine() : last; } boolean hasNext() { if (st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) { last = br.readLine(); st = new StringTokenizer(last); } } catch (Exception e) { return false; } return true; } String[] nextStrings(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = next(); return arr; } String[] nextLines(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = nextLine(); return arr; } int nextInt() throws IOException { return Integer.parseInt(next()); } int[] nextInts(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } Integer[] nextIntegers(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } int[][] next2Ints(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } long nextLong() throws IOException { return Long.parseLong(next()); } long[] nextLongs(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } long[][] next2Longs(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } double nextDouble() throws IOException { return Double.parseDouble(next().replace(',', '.')); } double[] nextDoubles(int size) throws IOException { double[] arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } boolean nextBool() throws IOException { String s = next(); if (s.equalsIgnoreCase("true") || s.equals("1")) return true; if (s.equalsIgnoreCase("false") || s.equals("0")) return false; throw new IOException("Boolean expected, String found!"); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
194efb487b759fc95c09d230d47f3f98
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
//package croc16; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; public class QC { static final String ADD = "http://"; static HashMap<String, HashSet<String>> hosts; static HashMap<String, String> hostStrings; static HashMap<String, ArrayList<String>> stringToHosts; static HashMap<String, HashSet<String>> sHosts; public class Path implements Comparable<Path>{ public int nPaths; public String paths; public Path(int nPaths,String paths) { this.nPaths = nPaths; this.paths = paths; } @Override public int compareTo(Path path) { if (this.nPaths < path.nPaths) return -1; else if (this.nPaths > path.nPaths) return 1; else return this.paths.compareTo(path.paths); } } public static void detectAlias() { // sort path of hosts for (Map.Entry<String, HashSet<String>> entry : hosts.entrySet()) { LinkedList<String> l = new LinkedList<>(entry.getValue()); Collections.sort(l); StringBuilder sb = new StringBuilder(); for (String path : l) { sb.append(path); } hostStrings.put(entry.getKey(), sb.toString()); } //System.out.println(hostStrings); // put in inverse for (Map.Entry<String, String> entry : hostStrings.entrySet()) { String path = entry.getValue(); String hostName = entry.getKey(); if (!stringToHosts.containsKey(path)) { ArrayList<String> hosts = new ArrayList<String>(); hosts.add(hostName); stringToHosts.put(path, hosts); } else { ArrayList<String> hosts = stringToHosts.get(path); hosts.add(hostName); } } //System.out.println(stringToHosts); StringBuilder sb = new StringBuilder(); int count = 0; for (Map.Entry<String, ArrayList<String>> entry : stringToHosts.entrySet()) { ArrayList<String> hosts = entry.getValue(); if (entry.getValue().size() > 1) { count++; for(String host: hosts) { sb.append(ADD + host + " "); } sb.deleteCharAt(sb.length()-1); sb.append("\n"); } } System.out.println(count); System.out.println(sb.toString()); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); // remove "\n" hosts = new HashMap<>(n); hostStrings = new HashMap<>(n); stringToHosts = new HashMap<>(n); for (int i = 1; i <= n; i++) { String address = sc.nextLine(); address = address.substring(ADD.length()); int pos = address.indexOf("/"); // get host name String hostName = address.substring(0, pos != -1? pos:address.length()); // get path String path = pos == -1? "/" : address.substring(pos) + "/"; // add to hosts if (hosts.containsKey(hostName)) { HashSet<String> paths = hosts.get(hostName); paths.add(path); } else { HashSet<String> paths = new HashSet<String>(); paths.add(path); hosts.put(hostName, paths); } } //System.out.println(hosts); detectAlias(); sc.close(); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
76c258810696b45c77c1c0c6b01167aa
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } private double NextDouble() { String n = inputParser.nextToken(); double val = Double.parseDouble(n); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } public static void main(String [] argv) { //String filePath="input.txt"; String filePath=null; if(argv.length>0)filePath=argv[0]; new C(filePath); } public C(String inputFile) { openInput(inputFile); //readNextLine(); int T=1;//NextInt(); StringBuilder sb = new StringBuilder(); for(int t=1; t<=T; t++) { readNextLine(); int N=NextInt(); HashMap <String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>(); HashSet <String> seen = new HashSet<String>(); for(int i=0; i<N; i++) { readNextLine(); if(seen.contains(line))continue; seen.add(line); String s = parseHostname(line); String a = parsePath(line); if(!hm.containsKey(s))hm.put(s, new ArrayList<String>()); hm.get(s).add(a); } HashMap <String, String> hm2 = new HashMap<String, String>(); for(String s:hm.keySet()) { Collections.sort(hm.get(s)); StringBuilder sbb = new StringBuilder(); for(String x:hm.get(s)) sbb.append(x+"#"); hm2.put(s, sbb.toString()); } HashMap <String, ArrayList<String>> res = new HashMap<String, ArrayList<String>>(); for(String s:hm2.keySet()) { if(!res.containsKey(hm2.get(s)))res.put(hm2.get(s), new ArrayList<String>()); res.get(hm2.get(s)).add(s); } int cnt=0; for(String x:res.keySet()) { if(res.get(x).size()>1) { for(String s:res.get(x)) sb.append(s+" "); sb.append("\n"); cnt++; } } sb.insert(0, cnt+"\n"); } System.out.print(sb); closeInput(); } String parseHostname(String s) { int pos = s.indexOf('/', 7); if(pos==-1)return s; return s.substring(0, pos); } String parsePath(String s) { int pos = s.indexOf('/', 7); if(pos==-1)return "@"; return s.substring(pos); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
d83ae55c6661f3ef29ee6cff9626590e
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
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.Collection; import java.util.Set; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.stream.Collectors; import java.util.TreeSet; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Map<String, Set<String>> paths = new HashMap<>(n, 1); for (int i = 0; i < n; i++) { String fullPath = in.next(); int slashPos; for (slashPos = 7; slashPos < fullPath.length(); slashPos++) { if (fullPath.charAt(slashPos) == '/') { break; } } String hostname = fullPath.substring(0, slashPos); String path = fullPath.substring(slashPos); paths.computeIfAbsent(hostname, key -> new TreeSet<>()) .add(path); } Map<String, List<String>> groups = new HashMap<>(); paths.forEach( (hostname, path) -> groups.computeIfAbsent(path.toString(), key -> new ArrayList<>()) .add(hostname)); List<String> result = groups.values().stream() .filter(hosts -> hosts.size() > 1) .map(hosts -> hosts.stream().map(Object::toString).collect(Collectors.joining(" "))) .collect(Collectors.toList()); out.printLine(result.size()); result.forEach(out::printLine); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
350fb3657fa51623e685ead71317de2c
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; /** * Created by wannabe on 17.03.16. */ public class C { public static void writeData(String data) throws IOException { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); log.write(data); log.flush(); } public static void main(String[] args) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { int n = Integer.parseInt(br.readLine()); Map<String, Set<String>> routes = new HashMap<>(); String line; String domain; String path; for (int i = 0; i < n; i++) { line = br.readLine().replaceFirst("http://", ""); domain = line.split("/")[0]; path = line.replaceFirst(domain, ""); if (routes.putIfAbsent(domain, new HashSet<>(Collections.singletonList(path))) != null) { routes.get(domain).add(path); } } Map<Set<String>, Set<String>> groups = new HashMap<>(); routes.values().stream() .forEach(s -> groups.put(s, new HashSet<>())); routes.entrySet().stream() .forEach(stringSetEntry -> groups.get(stringSetEntry.getValue()).add("http://" + stringSetEntry.getKey())); Set<String> result = groups.entrySet().stream() .filter(setSetEntry -> setSetEntry.getValue().size() > 1) .map(stringSetEntry -> stringSetEntry.getValue().stream().collect(Collectors.joining(" "))) .collect(Collectors.toSet()); String resStr = result.size() + "\n" + result.stream().collect(Collectors.joining("\n")); writeData(resStr); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
d06b41098db928d77083ce5a10012f9f
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; public class C implements Runnable{ final static Random rnd = new Random(); // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! static final String PREFIX = "http://"; static final char PATH_START = '/'; void solve() { int n = readInt(); Map<String, Set<Integer>> hostsPaths = new HashMap<>(); IdMap<String> pathIds = new IdMap<>(); for (int i = 0; i < n; ++i) { String fullPath = readLine(); fullPath = fullPath.substring(PREFIX.length()); int pathStartIndex = fullPath.indexOf(PATH_START); if (pathStartIndex == -1) pathStartIndex = fullPath.length(); String host = fullPath.substring(0, pathStartIndex); String path = fullPath.substring(pathStartIndex); int pathId = pathIds.getId(path); Set<Integer> hostPaths = hostsPaths.get(host); if (hostPaths == null) { hostsPaths.put(host, hostPaths = new HashSet<Integer>()); } hostPaths.add(pathId); } SortedMap<Integer[], List<String>> pathListsHosts = new TreeMap<>(new Comparator<Integer[]>() { @Override public int compare(Integer[] p1, Integer[] p2) { int minSize = min(p1.length, p2.length); for (int i = 0; i < minSize; ++i) { if (!p1[i].equals(p2[i])) { return p1[i] - p2[i]; } } return p1.length - p2.length; } }); for (Map.Entry<String, Set<Integer>> hostEntry : hostsPaths.entrySet()) { Set<Integer> hostPaths = hostEntry.getValue(); Integer[] hostPathsArray = hostPaths.toArray(new Integer[0]); Arrays.sort(hostPathsArray); List<String> pathListHosts = pathListsHosts.get(hostPathsArray); if (pathListHosts == null) { pathListsHosts.put(hostPathsArray, pathListHosts = new ArrayList<>()); } String host = hostEntry.getKey(); pathListHosts.add(host); } List<List<String>> answer = new ArrayList<>(); for (List<String> hostList : pathListsHosts.values()) { if (hostList.size() > 1) { answer.add(hostList); } } out.println(answer.size()); for (List<String> hostList : answer) { for (String host : hostList) { out.print(PREFIX + host + " "); } out.println(); } } int getAnswer(char[][] codes) { int answer = codes[0].length; for (char[] thisCode : codes) { for (char[] otherCode : codes) { if (otherCode == thisCode) continue; int equals = 0; for (int i = 0; i < thisCode.length; ++i) { equals += (thisCode[i] == otherCode[i] ? 1 : 0); } /* * 0 -> 2 * 1 -> 2 * 2 -> 1 * 3 -> 1 * 4 -> 0 * 5 -> 0 * * 6 - eq > 2k */ int maxPossibleErrors = (thisCode.length - equals + 1) / 2 - 1; answer = min(answer, maxPossibleErrors); } } return answer; } ///////////////////////////////////////////////////////////////////// final boolean FIRST_INPUT_STRING = false; final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; final static int MAX_STACK_SIZE = 128; ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { while (true) { try { solve(); out.println(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine()); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } char[] readCharArray() { return readLine().toCharArray(); } char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// int readInt() { return Integer.parseInt(readString()); } int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() { return Long.parseLong(readString()); } long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() { return Double.parseDouble(readString()); } double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() { return new BigInteger(readString()); } BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; protected int precision; protected String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; public RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants and functions //////////////// ///////////////////////////////////////////////////////////////////// static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; static final boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } static final boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// static final boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// static final long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } static final Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int getId(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
b975a50c56019f9679dddfd1c8440fa0
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; public class C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { int t = 1; while (t-- > 0) { solveTest(); } } class Host { String host; String x; TreeSet<String> paths; public Host(String host) { this.host = host; this.paths = new TreeSet<>(); } void build() { StringBuilder sb = new StringBuilder(); for(String s: paths) { sb.append(s); sb.append(";"); } x = sb.toString(); } } void solveTest() throws IOException { int n = readInt(); Map<String, Host> map = new TreeMap<>(); for (int i = 0; i < n; i++) { String cur = in.readLine(); int j = 0; int count = 0; for (; j < cur.length(); j++) { if (cur.charAt(j) == '/') { count++; if(count == 3) { break; } } } String host = cur.substring(0, j); String path = j == cur.length() ? " " : cur.substring(j); if(!map.containsKey(host)) { map.put(host, new Host(host)); } map.get(host).paths.add(path); } Host[] hosts = new Host[map.size()]; int size = 0; for(Map.Entry<String, Host> entry: map.entrySet()) { entry.getValue().build(); hosts[size++] = entry.getValue(); } Arrays.sort(hosts, (a, b) -> a.x.compareTo(b.x)); List<List<String>> res = new ArrayList<>(); List<String> cur = new ArrayList<>(); cur.add(hosts[0].host); for(int i = 1; i < hosts.length; i++) { if(hosts[i].x.compareTo(hosts[i-1].x) == 0) { cur.add(hosts[i].host); } else { if(cur.size() != 1) res.add(cur); cur = new ArrayList<>(); cur.add(hosts[i].host); } } if(cur.size() != 1) res.add(cur); out.println(res.size()); for(List<String> group: res) { int i = 0; for(String host: group) { out.print(host); if(i != group.size() - 1) out.print(" "); i++; } out.println(); } } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new C().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
9370db22252f25ce4203ac1bba4ea007
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; public class Croc2016QualC { public static StringTokenizer st; public static void nextLine(BufferedReader br) throws IOException { st = new StringTokenizer(br.readLine()); } public static String next() { return st.nextToken(); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static double nextDouble() { return Double.parseDouble(st.nextToken()); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); nextLine(br); int n = nextInt(); HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>(); for (int i = 0; i < n; i++) { nextLine(br); String s = next(); s = s.substring(7); String uri = ""; String hostname = ""; int slash = s.indexOf('/'); if (slash == -1) { hostname = s; } else { hostname = s.substring(0, slash); uri = s.substring(slash); } if (map.containsKey(hostname)) { map.get(hostname).add(uri); } else { HashSet<String> set = new HashSet<String>(); set.add(uri); map.put(hostname, set); } } HashMap<String, HashSet<String>> map2 = new HashMap<String, HashSet<String>>(); for (Map.Entry<String, HashSet<String>> entry : map.entrySet()) { String rep = represent(entry.getValue()); if (map2.containsKey(rep)) { map2.get(rep).add(entry.getKey()); } else { HashSet<String> set = new HashSet<String>(); set.add(entry.getKey()); map2.put(rep, set); } } List<Set<String>> ans = new ArrayList<Set<String>>(); for (Map.Entry<String, HashSet<String>> entry : map2.entrySet()) { if (entry.getValue().size() > 1) { ans.add(entry.getValue()); } } StringBuffer sb = new StringBuffer(); System.out.println(ans.size()); for (int i = 0; i < ans.size(); i++) { Set<String> set = ans.get(i); for (String s : set) { sb.append("http://" + s + " "); } sb.append("\n"); } System.out.println(sb.toString()); } public static String represent(HashSet<String> set) { ArrayList<String> list = new ArrayList<String>(); list.addAll(set); Collections.sort(list); return String.join(",", list); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
d602e0974ad1aa86bb95549f0215800b
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.util.*; import java.io.*; import java.util.stream.Stream; public class C { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); Map<String, Set<String>> map = new HashMap<>(); for (int i = 0; i < n; i++) { String s = in.next().substring(7); if (!s.contains("/")) { s += "/it's.more.than.20.letters"; } String[] ss = s.split("/", 2); if (!map.containsKey(ss[0])) { map.put(ss[0], new HashSet<>()); } map.get(ss[0]).add(ss[1]); } Map<Set<String>, List<String>> ans = new HashMap<>(); for (Map.Entry<String, Set<String>> pair : map.entrySet()) { if (!ans.containsKey(pair.getValue())) { ans.put(pair.getValue(), new ArrayList<>()); } ans.get(pair.getValue()).add(pair.getKey()); } out.println(ans.values().stream().filter(i -> i.size() != 1).count()); ans.values().stream().filter(i -> i.size() != 1).forEach(i -> { i.stream().forEach(x -> out.print("http://" + x + " ")); out.println(); }); } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); Locale.setDefault(Locale.US); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } 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()); } } public static void main(String[] arg) { new C().run(); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
b25a1e9a5468a59ed9bddab5daef52f5
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeSet; /* * 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. */ /** * * @author Gerasimov */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st = new StringTokenizer(inp.readLine()); int n = Integer.parseInt(st.nextToken()); HashMap<String, HashSet<String>> mas = new HashMap<>(); for (int i = 0; i < n; i++) { String s = inp.readLine(); int h = 0; String s1 = ""; String s2 = ""; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '/') { h++; } if (h == 3) { s1 = s.substring(0, j); s2 = s.substring(j); break; } } if (s1.isEmpty()) { s1 = s; } if (!mas.containsKey(s1)) { mas.put(s1, new HashSet<>()); } mas.get(s1).add(s2); } HashMap<HashSet<String>, HashSet<String>> res = new HashMap<>(); int res1=0; for (Map.Entry<String, HashSet<String>> entrySet : mas.entrySet()) { String key = entrySet.getKey(); HashSet<String> value = entrySet.getValue(); if (!res.containsKey(value)) { res.put(value, new HashSet<>()); } res.get(value).add(key); if (res.get(value).size()==2){ res1++; } } out.println(res1); for (Map.Entry<HashSet<String>, HashSet<String>> entrySet : res.entrySet()) { HashSet<String> value = entrySet.getValue(); if (value.size()>1){ for (String i : value) { out.print(i+" "); } out.println(); } } out.close(); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
811a59eafa87cb1b9e554911dc1c281b
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.*; /* http://codeforces.com/contest/644/problem/C Input The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); // number of pages HashMap<String, Paths> hashMap = new HashMap<>(); for (int i = 0; i < n; i++) { String url = in.next().substring(7); int pathIdx = url.indexOf('/'); if (pathIdx == -1) { pathIdx = url.length(); } String hostname = url.substring(0, pathIdx); String path = url.substring(pathIdx, url.length()); // out.println(hostname+" "+path); Paths paths; if (!hashMap.containsKey(hostname)) { paths = new Paths(); } else { paths = hashMap.get(hostname); } paths.add(path); hashMap.put(hostname, paths); } //System.out.println(hashMap); HashMap<Paths, Set<String>> stringHashMap = new HashMap<>(); for (String s : hashMap.keySet()) { Paths paths = hashMap.get(s); //if (paths.hashCode() != 0) { if (!stringHashMap.containsKey(paths)) { stringHashMap.put(paths, new HashSet<>()); } stringHashMap.get(paths).add(s); //} } //System.out.println(stringHashMap); for (Paths paths : new HashSet<>(stringHashMap.keySet())) { if (stringHashMap.get(paths).size() == 1) { stringHashMap.remove(paths); } } //System.out.println(stringHashMap); out.println(stringHashMap.size()); for (Paths paths : stringHashMap.keySet()) { Set<String> strings = stringHashMap.get(paths); for (String string : strings) { out.print("http://"+string+" "); } out.println(); } in.close(); out.close(); } } class Paths implements Comparable { private HashSet<String> strings = new HashSet<>(); private int hash = 0; public void add(String s) { if (!strings.contains(s)) { strings.add(s); hash += 31 * s.hashCode(); } } @Override public String toString() { return "Paths{" + "strings=" + strings + ", hash=" + hash + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Paths paths = (Paths) o; if (hash != paths.hash) return false; return strings != null ? strings.equals(paths.strings) : paths.strings == null; } @Override public int hashCode() { return hash; } @Override public int compareTo(Object o) { Paths paths = (Paths) o; return hash - paths.hashCode(); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
f767896b528b93a47c4a8b697d519016
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.Scanner; import java.util.Set; import java.util.HashMap; import java.util.stream.Collectors; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.stream.Stream; import java.util.Map; import java.util.Map.Entry; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Artyom Korzun */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static @SuppressWarnings("Duplicates") class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); Map<String, Set<String>> pathsByHost = new HashMap<>(); for (int i = 0; i < n; i++) { String url = in.next(); int index = url.indexOf('/', 7); String host = (index == -1) ? url : url.substring(0, index); String path = (index == -1) ? "" : url.substring(index); pathsByHost.computeIfAbsent(host, key -> new HashSet<>()).add(path); } Map<Set<String>, List<String>> hostsByPaths = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : pathsByHost.entrySet()) { String host = entry.getKey(); Set<String> paths = entry.getValue(); hostsByPaths.computeIfAbsent(paths, key -> new ArrayList<>()).add(host); } List<Map.Entry<Set<String>, List<String>>> answer = hostsByPaths.entrySet() .stream() .filter(entry -> (entry.getValue().size() > 1)) .collect(Collectors.toList()); out.println(answer.size()); answer.forEach(entry -> { entry.getValue().forEach(host -> out.print(host + " ")); out.println(); }); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
341d34ab578efd91bf2e4b164a3ce169
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class C implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start(); new C().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); initHashThings(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private void initHashThings() { Random rnd = new Random(); int n = 100000 * 30 + 5; int prime1 = BigInteger.valueOf(3000 + rnd.nextInt(500)) .nextProbablePrime().intValue(); int prime2 = BigInteger.valueOf(4000 + rnd.nextInt(500)) .nextProbablePrime().intValue(); mod1 = BigInteger.valueOf((int) 1e9 + rnd.nextInt(500)) .nextProbablePrime().intValue(); mod2 = BigInteger.valueOf((int) 1e9 + (int) 1e6 + rnd.nextInt(500)) .nextProbablePrime().intValue(); pow1 = new int[n]; pow2 = new int[n]; pow1[0] = pow2[0] = 1; for (int i = 1; i < n; i++) { pow1[i] = (int) ((long) pow1[i - 1] * prime1 % mod1); pow2[i] = (int) ((long) pow2[i - 1] * prime2 % mod2); } } int mod1, mod2; int[] pow1, pow2; int getHash(char[] s, int[] pow, int mod) { int h = s[0]; for (int i = 1; i < s.length; i++) { h = (int) ((h + (long) pow[i] * s[i]) % mod); } return h; } long getHash(char[] s) { int hash1 = getHash(s, pow1, mod1); int hash2 = getHash(s, pow2, mod2); return ((long) hash1 << 32) | hash2; } void solve() throws IOException { int n = readInt(); Map<String, Set<String>> addressesForHost = new HashMap<>(); for (int i = 0; i < n; i++) { String url = readString().replace("http://", ""); String host, address; if (!url.contains("/")) { host = url; address = "#"; } else { host = url.substring(0, url.indexOf("/")); address = url.substring(url.indexOf("/")); } //out.println(host + " " + address); Set<String> addresses = addressesForHost.get(host); if (addresses == null) { addresses = new HashSet<>(); addressesForHost.put(host, addresses); } addresses.add(address); } Map<Long, List<String>> groups = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : addressesForHost.entrySet()) { String host = entry.getKey(); Set<String> addresses = entry.getValue(); List<String> sortedAddresses = new ArrayList<>(); sortedAddresses.addAll(addresses); Collections.sort(sortedAddresses); StringBuilder sb = new StringBuilder(); for (String address : sortedAddresses) { sb.append("%"); sb.append(address); sb.append("%"); } char[] completeAddress = sb.toString().toCharArray(); long hash = getHash(completeAddress); List<String> groupMembers = groups.get(hash); if (groupMembers == null) { groupMembers = new ArrayList<>(); groups.put(hash, groupMembers); } //out.println(host + " " + sb.toString()); groupMembers.add("http://" + host); } List<List<String>> answer = new ArrayList<>(); for (Map.Entry<Long, List<String>> entry : groups.entrySet()) { if (entry.getValue().size() > 1) { answer.add(entry.getValue()); } } out.println(answer.size()); for (List<String> group : answer) { for (String site : group) { out.print(site + " "); } out.println(); } } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
5b9310677c303fc5bd61019377855c13
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.security.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } try { hasher = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private MessageDigest hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, MessageDigest md) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = md.digest(joinedPathes.getBytes()); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } return compareArrays(hashes, other.hashes); } private int compareArrays(byte[] a1, byte[] a2) { for (int i = 0; i < a1.length; ++i) { if (a1[i] != a2[i]) { return a1[i] < a2[i] ? -1 : 1; } } return 0; } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append("!&)"); sb.append(i); } return sb.toString(); } private int pathesCount; private byte[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { this.size = size; hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
11a56ead6f9f5342285c559426217f7b
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.stream.Collectors.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public Solver(InputReader reader) throws IOException { create(); int n = reader.nextUInt(); for (int i = 0; i < n; ++i) { String address = reader.next(); int p = address.indexOf("/", 7); p = p == -1 ? address.length() : p; servers.get(address.substring(0, p)).add(address.substring(p)); } } public void run(PrintWriter writer) { servers.entrySet() .stream() .forEach(server -> sites.get(fix(server.getValue())).add(server.getKey())); List<List<String>> r = sites.entrySet() .stream() .filter(site -> site.getValue().size() > 1) .map(site -> site.getValue()) .collect(toList()); writer.println(r.size()); r.stream() .map(site -> String.join(" ", site)) .forEach(writer::println); } private List<String> fix(List<String> lst) { temp.addAll(lst); lst.clear(); lst.addAll(temp); temp.clear(); return lst; } private void create() { temp = new TreeSet<>(); servers = new SmartHashMap<>(ArrayList::new); sites = new SmartHashMap<>(ArrayList::new); } private Set<String> temp; private Map<String, List<String>> servers; private Map<List<String>, List<String>> sites; } class SmartHashMap<K, V> extends HashMap<K, V> { public SmartHashMap(Supplier<V> keyFactory) { this.keyFactory = keyFactory; } @Override public V get(Object okey) { K key = (K) okey; V value = super.get(key); if (value == null) { put(key, value = keyFactory.get()); } return value; } private Supplier<V> keyFactory; } class InputReader { private static final int BUFFER_SIZE = (1 << 16)-1; private int cursor; private byte[] buffer; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; cursor = BUFFER_SIZE; buffer = new byte[BUFFER_SIZE]; } private void readAhead(int amount) throws IOException { int remaining = BUFFER_SIZE^cursor; if (remaining < amount) { System.arraycopy(buffer, cursor, buffer, 0, remaining); int size = remaining + stream.read(buffer, remaining, cursor); cursor = 0; if (size < BUFFER_SIZE) { Arrays.fill(buffer, size, BUFFER_SIZE, (byte) 0); } } } private byte read() { return buffer[cursor++]; } private boolean isSpace(byte c) { return c == 0 || c == 32 || c == 13 || c == 10; } private byte skipSpaces() throws IOException { readAhead(1<<6); byte c = read(); while (isSpace(c)) { c = read(); } return c; } private int readU31(byte c) { int r = 0; while (!isSpace(c)) { r = (r<<3) + (r<<1) + (c&15); c = read(); } return r; } public String next() throws IOException { byte c = skipSpaces(); int beginPosition = cursor; while (!isSpace(c)) { c = read(); } return new String(buffer, beginPosition-1, cursor-beginPosition); } public int nextUInt() throws IOException { return readU31(skipSpaces()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
96294b3cffda9e998c4277a57653176a
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.StringTokenizer; import java.util.Queue; import java.util.ArrayDeque; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { long startTime = System.currentTimeMillis(); boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } if (!oj) { System.out.println("Execution time: " + (System.currentTimeMillis()-startTime)/1000.0); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); int multiCount = 0; for (Host host: hosts) { if (add(host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(Host host) { HostDescriptor desc = new HostDescriptor(host); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public static final int BASE1 = 127; public static final int BASE2 = 131; public static final long MOD2 = 1_000_000_007; public static final long MOD1 = 1_000_000_009; public HostDescriptor(Host host) { hash1 = 123419; hash2 = 13417; aliaseCount = 1; size = host.pathes.size(); for (String s: host.pathes) { add(s); } names = new ArrayList<String>(); names.add(host.name); pathes = new ArrayList<String>(host.pathes); } public boolean addName(String name) { names.add(name); return aliaseCount++ == 1; } public boolean isMulti() { return aliaseCount > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: names) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (size != other.size) { return size - other.size; } else if (hash1 != other.hash1) { return hash1 < other.hash1 ? -1 : 1; } else if (hash2 != other.hash2) { return hash2 < other.hash2 ? -1 : 1; } else { return comparePathes(other.pathes); } } private int comparePathes(List<String> otherPathes) { for (int i = 0; i < size; ++i) { int cmp = pathes.get(i).compareTo(otherPathes.get(i)); if (cmp != 0) { return cmp; } } return 0; } private void add(String s) { hash1 *= MOD2; hash1 %= MOD1; hash2 *= MOD1; hash2 %= MOD2; for (char c: s.toCharArray()) { hash1 *= BASE1; hash1 += c&127; hash1 %= MOD1; hash2 *= BASE2; hash2 += c&127; hash2 %= MOD2; } } private int aliaseCount; private int size; private long hash1; private long hash2; private List<String> names; private List<String> pathes; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
b89ba58c7fb9fd188dcbdbcaad72da8d
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final String HTTP_PREFIX = "http://"; public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { int n = reader.nextInt(); servers = new TreeMap<String, Set<String>>(); for (int i = 0; i < n; ++i) { addServer(reader.next()); } } public void run(PrintWriter writer) { sites = new HashMap<Set<String>, List<String>>(); int multiCount = 0; for (Map.Entry<String, Set<String>> server: servers.entrySet()) { List<String> aliases = sites.get(server.getValue()); if (aliases == null) { aliases = new ArrayList<String>(); sites.put(server.getValue(), aliases); } aliases.add(server.getKey()); if (aliases.size() == 2) { ++multiCount; } } writer.println(multiCount); for (Map.Entry<Set<String>, List<String>> site: sites.entrySet()) { if (site.getValue().size() > 1) { for (String alias: site.getValue()) { writer.print(HTTP_PREFIX + alias); writer.print(' '); } writer.println(); } } } private void addServer(String address) { int p = address.indexOf("/", HOST_NAME_BEGIN_POSITION); String host = getHost(p, address); Set<String> server = servers.get(host); if (server == null) { server = new TreeSet<String>(); servers.put(host, server); } server.add(getPath(p, address)); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private Map<String, Set<String>> servers; private Map<Set<String>, List<String>> sites; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
b98f815436bf5dd2119c3eaac5d859c7
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { long startTime = System.currentTimeMillis(); boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } if (!oj) { System.out.println("Execution time: " + (System.currentTimeMillis()-startTime)/1000.0); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } hasher = new StringMultiHasher(2); } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private IStringMultiHasher hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, IStringMultiHasher hasher) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = hasher.getHash(joinedPathes); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } int cmp = StringMultiHasher.compareArrays(hashes, other.hashes); return cmp != 0 ? cmp : joinedPathes.compareTo(other.joinedPathes); } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append('$'); sb.append(i); } return sb.toString(); } private int pathesCount; private int[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
3a5cbf2a3d95ff504c31a28ffff09311
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public Solver(InputReader reader) throws IOException { int n = reader.nextInt(); servers = new HashMap<>(); for (int i = 0; i < n; ++i) { addServer(reader.next()); } temp = new TreeSet<>(); } public void run(PrintWriter writer) { sites = new HashMap<>(); int multiCount = 0; for (Map.Entry<String, List<String>> server: servers.entrySet()) { fix(server.getValue()); List<String> aliases = sites.get(server.getValue()); if (aliases == null) { sites.put(server.getValue(), aliases = new ArrayList<>()); } aliases.add(server.getKey()); if (aliases.size() == 2) { ++multiCount; } } writer.println(multiCount); for (Map.Entry<List<String>, List<String>> site: sites.entrySet()) { if (site.getValue().size() > 1) { writer.println(String.join(" ", site.getValue())); } } } private void addServer(String address) { int p = address.indexOf("/", 7); if (p == -1) { p = address.length(); } String host = address.substring(0, p); List<String> server = servers.get(host); if (server == null) { servers.put(host, server = new ArrayList<>()); } server.add(address.substring(p)); } private void fix(List<String> lst) { temp.addAll(lst); lst.clear(); lst.addAll(temp); temp.clear(); } private Set<String> temp; private Map<String, List<String>> servers; private Map<List<String>, List<String>> sites; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
77ecdeff4b1ba9a1a369dc0c96538f44
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.security.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } try { hasher = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private MessageDigest hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, MessageDigest md) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = md.digest(joinedPathes.getBytes()); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } return compareArrays(hashes, other.hashes); } private int compareArrays(byte[] a1, byte[] a2) { for (int i = 0; i < a1.length; ++i) { if (a1[i] != a2[i]) { return a1[i] < a2[i] ? -1 : 1; } } return 0; } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append("!&)"); sb.append(i); } return sb.toString(); } private int pathesCount; private byte[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { this.size = size; hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
500bfaed2fe1e8d901ad01786ad59d5c
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.security.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } try { hasher = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private MessageDigest hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, MessageDigest md) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = md.digest(joinedPathes.getBytes()); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } return compareArrays(hashes, other.hashes); } private int compareArrays(byte[] a1, byte[] a2) { for (int i = 0; i < a1.length; ++i) { if (a1[i] != a2[i]) { return a1[i] < a2[i] ? -1 : 1; } } return 0; } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append("!&)"); sb.append(i); } return sb.toString(); } private int pathesCount; private byte[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { this.size = size; hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
42d443324cef1101af1c128b35b238ee
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } hasher = new StringMultiHasher(10); } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private IStringMultiHasher hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, IStringMultiHasher hasher) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = hasher.getHash(joinedPathes); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } int cmp = StringMultiHasher.compareArrays(hashes, other.hashes); return cmp;//cmp != 0 ? cmp : joinedPathes.compareTo(other.joinedPathes); } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append('$'); sb.append(i); } return sb.toString(); } private int pathesCount; private int[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { this.size = size; hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
64e347cc39689ec67c40728897e1cd81
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } trie = new Trie(""); multiCount = 0; temp = new Host(""); hosts = new TreeSet<>(); } public void run(PrintWriter writer) throws IOException { for (String s: a) { add(s); } StringBuilder sb = new StringBuilder(); for (Host host: hosts) { trie.add(unite(sb, host), host.name); } writer.println(multiCount); trie.print(writer); } private String unite(StringBuilder sb, Host host) { sb.setLength(0); for (String path: host.pathes) { sb.append(path); sb.append('$'); } return sb.toString(); } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private Trie trie; private int n; private String[] a; private int multiCount; class Trie { public static final int ALPHABET_SIZE = 1<<7; public Trie(String t) { this.t = t; edges = new Trie[ALPHABET_SIZE]; } public Trie(String t, String info) { this(t); setLeaf(info); } public void add(String s, String info) { add(s, null, info); } public void add(String s, Trie parent, String info) { for (int i = 0; i < min(s.length(), t.length()); ++i) { if (s.charAt(i) != t.charAt(i)) { split(i, s, parent, info); return; } } if (s.length() == t.length()) { setLeaf(info); } else if (s.length() < t.length()) { split(s.length(), s, parent, info); } else { int i = getIndex(s.charAt(t.length())); if (edges[i] != null) { edges[i].add(s.substring(t.length()), this, info); } else { edges[i] = new Trie(s.substring(t.length()), info); } } } public void print(PrintWriter writer) { if (infos != null && infos.size() > 1) { writer.print("http://"); writer.print(infos.get(0)); for (int i = 1; i < infos.size(); ++i) { writer.print(" http://"); writer.print(infos.get(i)); } writer.println(); } for (int i = 0; i < ALPHABET_SIZE; ++i) { if (edges[i] != null) { edges[i].print(writer); } } } private void split(int i, String s, Trie parent, String info) { String commonPrefix = s.substring(0, i); Trie common = i == s.length() ? new Trie(commonPrefix, info) : new Trie(commonPrefix); parent.edges[getIndex(commonPrefix)] = common; t = t.substring(i); common.edges[getIndex(t)] = this; if (i < s.length()) { s = s.substring(i); common.edges[getIndex(s)] = new Trie(s, info); } } private int getIndex(String s) { return s.charAt(0); } private int getIndex(char c) { return c; } private boolean isLeaf() { return infos != null; } private void setLeaf(String info) { if (infos == null) { infos = new ArrayList<String>(); } infos.add(info); if (infos.size() == 2) { ++multiCount; } } private List<String> infos; private String t; private Trie edges[]; } } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
0e7d8d6416156a5b117cf2d8a7a1d2b0
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final String HTTP_PREFIX = "http://"; public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { int n = reader.nextInt(); servers = new HashMap<String, Set<String>>(); for (int i = 0; i < n; ++i) { addServer(reader.next()); } } public void run(PrintWriter writer) { sites = new HashMap<Set<String>, List<String>>(); int multiCount = 0; for (Map.Entry<String, Set<String>> server: servers.entrySet()) { List<String> aliases = sites.get(server.getValue()); if (aliases == null) { sites.put(server.getValue(), aliases = new ArrayList<>()); } aliases.add(server.getKey()); if (aliases.size() == 2) { ++multiCount; } } writer.println(multiCount); for (Map.Entry<Set<String>, List<String>> site: sites.entrySet()) { if (site.getValue().size() > 1) { for (String alias: site.getValue()) { writer.print(HTTP_PREFIX + alias); writer.print(' '); } writer.println(); } } } private void addServer(String address) { int p = address.indexOf("/", HOST_NAME_BEGIN_POSITION); if (p == -1) { p = address.length(); } String host = address.substring(HOST_NAME_BEGIN_POSITION, p); Set<String> server = servers.get(host); if (server == null) { servers.put(host, server = new HashSet<>()); } server.add(address.substring(p)); } private Map<String, Set<String>> servers; private Map<Set<String>, List<String>> sites; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
a69cb6e2eb39e84b777fce1bde981049
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { long startTime = System.currentTimeMillis(); boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } if (!oj) { System.out.println("Execution time: " + (System.currentTimeMillis()-startTime)/1000.0); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } hasher = new StringMultiHasher(3); } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private IStringMultiHasher hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, IStringMultiHasher hasher) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = hasher.getHash(joinedPathes); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } int cmp = StringMultiHasher.compareArrays(hashes, other.hashes); return cmp != 0 ? cmp : joinedPathes.compareTo(other.joinedPathes); } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append('$'); sb.append(i); } return sb.toString(); } private int pathesCount; private int[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
9052832551088653c404ad281dd9c24d
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.stream.Collectors.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public Solver(InputReader reader) throws IOException { create(); int n = reader.nextUInt(); for (int i = 0; i < n; ++i) { String address = reader.next(); int p = address.indexOf("/", 7) == -1 ? address.length() : address.indexOf("/", 7); servers.get(address.substring(0, p)).add(address.substring(p)); } } public void run(PrintWriter writer) { servers.entrySet() .stream() .forEach(server -> sites.get(fix(server.getValue())).add(server.getKey())); List<List<String>> answer = sites.entrySet() .stream() .filter(site -> site.getValue().size() > 1) .map(site -> site.getValue()) .collect(toList()); writer.println(answer.size()); answer.stream() .map(site -> String.join(" ", site)) .forEach(writer::println); } private List<String> fix(List<String> lst) { temp.addAll(lst); lst.clear(); lst.addAll(temp); temp.clear(); return lst; } private void create() { temp = new TreeSet<>(); servers = new SmartHashMap<>(ArrayList::new); sites = new SmartHashMap<>(ArrayList::new); } private Set<String> temp; private Map<String, List<String>> servers; private Map<List<String>, List<String>> sites; } class SmartHashMap<K, V> extends HashMap<K, V> { public SmartHashMap(Supplier<V> keyFactory) { this.keyFactory = keyFactory; } @Override public V get(Object okey) { K key = (K) okey; V value = super.get(key); if (value == null) { put(key, value = keyFactory.get()); } return value; } private Supplier<V> keyFactory; } class InputReader { private static final int BUFFER_SIZE = (1 << 16)-1; private int cursor; private byte[] buffer; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; cursor = BUFFER_SIZE; buffer = new byte[BUFFER_SIZE]; } private void readAhead(int amount) throws IOException { int remaining = BUFFER_SIZE^cursor; if (remaining < amount) { System.arraycopy(buffer, cursor, buffer, 0, remaining); int size = remaining + stream.read(buffer, remaining, cursor); cursor = 0; if (size < BUFFER_SIZE) { Arrays.fill(buffer, size, BUFFER_SIZE, (byte) 0); } } } private byte read() { return buffer[cursor++]; } private boolean isDigit(byte c) { return c >= 48 && c <= 57; } private boolean isSpaceChar(byte c) { return c == 13 || c == 10; } private byte begin() throws IOException { readAhead(1<<5); byte c = read(); while (!isDigit(c) && c != '-') { c = read(); } return c; } private int readU31(byte c) { int r = 0; while (isDigit(c)) { r = (r<<3) + (r<<1) + (c&15); c = read(); } return r; } public String next() throws IOException { readAhead(1<<6); byte c = read(); while (isSpaceChar(c)) { c = read(); } int beginPosition = cursor-1; while (!isSpaceChar(c)) { c = read(); } return new String(buffer, beginPosition, cursor-beginPosition-1); } public int nextUInt() throws IOException { return readU31(begin()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
70a4a4f24393b462d6e81a53aa7181ff
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final String HTTP_PREFIX = "http://"; public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { int n = reader.nextInt(); servers = new HashMap<>(); for (int i = 0; i < n; ++i) { addServer(reader.next()); } temp = new TreeSet<>(); } public void run(PrintWriter writer) { sites = new HashMap<>(); int multiCount = 0; for (Map.Entry<String, List<String>> server: servers.entrySet()) { fix(server.getValue()); List<String> aliases = sites.get(server.getValue()); if (aliases == null) { sites.put(server.getValue(), aliases = new ArrayList<>()); } aliases.add(server.getKey()); if (aliases.size() == 2) { ++multiCount; } } writer.println(multiCount); for (Map.Entry<List<String>, List<String>> site: sites.entrySet()) { if (site.getValue().size() > 1) { for (String alias: site.getValue()) { writer.print(HTTP_PREFIX + alias); writer.print(' '); } writer.println(); } } } private void addServer(String address) { int p = address.indexOf("/", HOST_NAME_BEGIN_POSITION); if (p == -1) { p = address.length(); } String host = address.substring(HOST_NAME_BEGIN_POSITION, p); List<String> server = servers.get(host); if (server == null) { servers.put(host, server = new ArrayList<>()); } server.add(address.substring(p)); } private void fix(List<String> lst) { temp.addAll(lst); lst.clear(); lst.addAll(temp); temp.clear(); } private Set<String> temp; private Map<String, List<String>> servers; private Map<List<String>, List<String>> sites; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
64b442a5900effed4b0c3e87c6706f48
train_003.jsonl
1458118800
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; — server name (consists of words and maybe some dots separating them), /&lt;path&gt; — optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versa — for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.StrictMath.*; public class HostnameAliases { private static final String INPUT_FILE = "input.txt"; private static final String ONLINE_JUDGE = "ONLINE_JUDGE"; public static void main(String[] args) { boolean oj = System.getProperty(ONLINE_JUDGE) != null; try { InputReader reader = new InputReader(oj ? System.in : new FileInputStream(INPUT_FILE)); PrintWriter writer = new PrintWriter(System.out); new Solver(reader).run(writer); writer.close(); } catch (IOException e) { new RuntimeException(e); } } } class Solver { public static final int HOST_NAME_BEGIN_POSITION = 7; public Solver(InputReader reader) throws IOException { n = reader.nextInt(); a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = reader.next(); } hasher = new StringMultiHasher(2); } public void run(PrintWriter writer) throws IOException { hosts = new TreeSet<>(); temp = new Host(""); for (String s: a) { add(s); } descriptors = new TreeSet<>(); StringBuilder sb = new StringBuilder(); int multiCount = 0; for (Host host: hosts) { if (add(sb, host)) { ++multiCount; } } writer.println(multiCount); for (HostDescriptor desc: descriptors) { if (desc.isMulti()) { desc.print(writer); } } } private boolean add(StringBuilder sb, Host host) { HostDescriptor desc = new HostDescriptor(host, sb, hasher); HostDescriptor exist = descriptors.floor(desc); if (exist != null && exist.compareTo(desc) == 0) { return exist.addName(host.name); } else { descriptors.add(desc); return false; } } private void add(String address) { int p = findBeginPathPosition(address); String host = getHost(p, address); String path = getPath(p, address); add(host, path); } private void add(String host, String path) { temp.name = host; Host h = hosts.floor(temp); if (h == null || !h.name.equals(host)) { h = new Host(host); hosts.add(h); } h.pathes.add(path); } private String getHost(int p, String address) { return p == -1 ? address.substring(HOST_NAME_BEGIN_POSITION) : address.substring(HOST_NAME_BEGIN_POSITION, p); } private String getPath(int p, String address) { return p == -1 ? "" : address.substring(p); } private int findBeginPathPosition(String address) { return address.indexOf("/", HOST_NAME_BEGIN_POSITION); } private Host temp; private TreeSet<Host> hosts; private IStringMultiHasher hasher; private TreeSet<HostDescriptor> descriptors; private int n; private String[] a; } class Host implements Comparable<Host> { public Host(String name) { this.name = name; pathes = new TreeSet<String>(); } @Override public int compareTo(Host other) { return name.compareTo(other.name); } String name; Set<String> pathes; } class HostDescriptor implements Comparable<HostDescriptor> { public HostDescriptor(Host host, StringBuilder sb, IStringMultiHasher hasher) { pathesCount = host.pathes.size(); joinedPathes = join(sb, host.pathes); hashes = hasher.getHash(joinedPathes); aliases = new ArrayList<String>(); aliases.add(host.name); } public boolean addName(String name) { aliases.add(name); return aliases.size() == 2; } public boolean isMulti() { return aliases.size() > 1; } public void print(PrintWriter writer) { boolean first = true; for (String name: aliases) { if (first) { first = false; } else { writer.print(' '); } writer.print("http://"); writer.print(name); } writer.println(); } @Override public int compareTo(HostDescriptor other) { if (pathesCount != other.pathesCount) { return pathesCount - other.pathesCount; } int cmp = StringMultiHasher.compareArrays(hashes, other.hashes); return cmp;//cmp != 0 ? cmp : joinedPathes.compareTo(other.joinedPathes); } private String join(StringBuilder sb, Set<String> l) { sb.setLength(0); for (String i: l) { sb.append('$'); sb.append(i); } return sb.toString(); } private int pathesCount; private int[] hashes; private String joinedPathes; private List<String> aliases; } interface IStringMultiHasher { public int[] getHash(String s); } class StringMultiHasher implements IStringMultiHasher { public StringMultiHasher(int size) { this.size = size; hasher = new IStringHasher[size]; for (int i = 0; i < size; ++i) { hasher[i] = new StringHasher(); } } @Override public int[] getHash(String s) { int[] r = new int[size]; for (int i = 0; i < size; ++i) { r[i] = hasher[i].getHash(s); } return r; } private int size; private IStringHasher hasher[]; public static int compareArrays(int[] a, int[] b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b[i]) { return a[i]-b[i]; } } return 0; } } interface IStringHasher { public int getHash(String s); } class StringHasher implements IStringHasher { public static final int MIN_BASE = 127; public static final int MAX_BASE = 255; public static final int MIN_MODULE = 1_000_000; public static final int MAX_MODULE = 2_000_000; public StringHasher() { Random rng = getRNG(); base = getNextPrime(getRandom(MIN_BASE, MAX_BASE, rng)); module = getNextPrime(getRandom(MIN_MODULE, MAX_MODULE, rng)); init = rng.nextInt(module); } @Override public int getHash(String s) { int hash = init; for (char c: s.toCharArray()) { hash *= base; hash += c; hash %= module; } return hash; } private int getNextPrime(int x) { while (!isPrime(x)) { ++x; } return x; } private int getRandom(int lo, int hi, Random rng) { return lo + rng.nextInt(hi-lo); } private boolean isPrime(int x) { for (int i = 2; i*i <= x; ++i) { if (x%i == 0) { return false; } } return true; } private Random getRNG() { return new Random(calls++); } private static int calls; private int init; private int base; private int module; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test", "14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a"]
5 seconds
["1\nhttp://abacaba.de http://abacaba.ru", "2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc"]
null
Java 8
standard input
[ "implementation", "*special", "sortings", "data structures", "binary search", "strings" ]
9b35f7df9e21162858a8fac8ee2837a4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.
2,100
First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.
standard output
PASSED
f01d8887b6ca02d72d54306666b8f2b5
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; public class A { int[] p, d; void solve() throws IOException { in("__std"); out("__std"); int n = readInt(); p = new int[n]; for (int i = 0; i < n; ++i) { p[i] = readInt() - 1; } d = new int[n]; int max = 0; for (int i = 0; i < n; ++i) { max = Math.max(max, dfs(i)); } println(max); exit(); } int dfs(int i) { if (d[i] == 0) { d[i] = 1; if (p[i] >= 0) { d[i] += dfs(p[i]); } } return d[i]; } void in(String name) throws IOException { if (name.equals("__std")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals("__std")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new A().solve(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
e4fa8284c07cab1575f7b313d89b02f7
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedInputStream; import java.util.*; import static java.lang.Math.*; public class C116C { private int dfs(int[] arr, int i) { int res = 0; while(arr[i] != -2) { i = arr[i]; res++; } return res; } public void solve() throws Exception { int n = nextInt(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = nextInt() - 1; } int res = 0; for (int i = 0; i < arr.length; i++) { res = max(dfs(arr, i) + 1, res); } println(res); } // ------------------------------------------------------ void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } void print(Object... os) { if (os != null && os.length > 0) System.out.print(os[0].toString()); for (int i = 1; i < os.length; ++i) System.out.print(" " + os[i].toString()); } void println(Object... os) { print(os); System.out.println(); } BufferedInputStream bis = new BufferedInputStream(System.in); String nextWord() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c > ' ') { sb.append(c); c = (char) bis.read(); } return new String(sb); } String nextLine() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c != '\n' && c != '\r') { sb.append(c); c = (char) bis.read(); } return new String(sb); } int nextInt() throws Exception { return Integer.parseInt(nextWord()); } long nextLong() throws Exception { return Long.parseLong(nextWord()); } public static void main(String[] args) throws Exception { new C116C().solve(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
22de2ea07325aa2c1812229adb7667a4
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.util.*; public class C116 implements Runnable{ public static void main(String args[]){ new C116().run(); } @Override 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){ e.printStackTrace(); System.exit(0); } } int nextInt()throws IOException{ return Integer.parseInt(nextToken()); } double nextDouble()throws IOException{ return Double.parseDouble(nextToken()); } long nextLong() throws IOException{ return Long.parseLong(nextToken()); } String nextToken()throws IOException{ while(tok == null || !tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } BufferedReader in; PrintWriter out; StringTokenizer tok; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// private void solve()throws IOException{ int N = nextInt(); int[] p = new int[N]; int[] depth = new int[N]; for(int i = 0; i < N; i++)p[i] = nextInt() - 1; int ans = 0; for(int i = 0; i < N; i++){ depth[i] = calcdepth(i, p, depth); ans = Math.max(ans, depth[i]); } out.println(ans); } private int calcdepth(int at, int[] p, int[] depth){ if(p[at] < 0) return 1; return calcdepth(p[at], p, depth) + 1; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
0d30f9f7f43ed5ef8190ecc634f6a97f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 9/15/11 * Time: 5:46 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.util.*; public class TaskA extends Thread { public TaskA() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } private void solve() throws Throwable { int n = nextInt(); g = new ArrayList [n]; boolean is[] = new boolean[n]; for (int i = 0; i < n; ++i) { g[i] = new ArrayList<Integer>(); } d = new Integer[n]; for (int i = 0; i < n; ++i) { int from = nextInt(); if (from != -1) { g[from - 1].add(i); is[i] = true; } } Arrays.fill(d, -1); for (int i = 0; i < n; ++i) { if (!is[i]) { Queue<Integer> q = new ArrayDeque<Integer>(); d[i] = 0; q.add(i); while (!q.isEmpty()) { int from = q.poll(); for (int to : g[from]) { d[to] = d[from] + 1; q.add(to); } } } } output.println(Collections.max(Arrays.asList(d)) + 1); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new TaskA().start(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private ArrayList<Integer> g[]; Integer []d; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
fc5b18a7fca2f9c561926b4fa02603dd
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import javax.sound.sampled.Line; import java.awt.Point; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.*; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; public class A{ void solve()throws Exception { int n = nextInt(); int[] p = new int[n]; ArrayList<Integer>[] child = new ArrayList[n]; for (int i = 0; i < n; i++) child[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = nextInt(); if (x != -1) x--; p[i] = x; if (x != -1) child[x].add(i); } int res=0; for (int i = 0; i < n; i++) if (p[i] == -1) { ArrayList<Integer> l = new ArrayList<Integer>(); l.add(i); int d = 0; while (l.size() > 0) { d++; ArrayList<Integer> next = new ArrayList<Integer>(); for (int x : l) for (int y : child[x]) next.add(y); l=next; } res = Math.max(res,d); } System.out.println(res); } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(new PrintWriter(System.out)); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new A().run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
e3692b1a2c7d42408b563552b613a5e8
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.StringTokenizer; /** * Date 02.11.2011 * Time 15:07:52 * Author Woodey * $ */ public class A115 { boolean used[]; ArrayList<Integer> graph[]; private void Solution() throws IOException { int n = nextInt(), ans = 0; used = new boolean[n]; graph = new ArrayList[n]; ArrayList<Integer> v = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) graph[i] = new ArrayList<Integer>(); for (int i = 0; i < n; i ++) { int a = nextInt(); if (a == -1) { v.add(i); continue; } a --; graph[i].add(a); graph[a].add(i); } for (int i = 0; i < v.size(); i ++) ans = Math.max(ans, depth(v.get(i))); System.out.println(ans+1); } int depth(int v) { used[v] = true; int res = 0; for (int i: graph[v]) if(!used[i]) res = Math.max(res, depth(i)+1); return res; } public static void main(String[] args) { new A115().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(1); } } 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
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
bb83d0d34417050825485b7d5d62bc9f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.DataOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; public class A115Holiday { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); int[] input = new int[n]; int[] graphMap = new int[n]; boolean[] visites = new boolean[n]; List<Graph<Integer>> graphs = new ArrayList<Graph<Integer>>(); for (int i = 0; i < n; i++) input[i] = Integer.parseInt(scanner.nextLine()) - 1; // int graphNum = 0; // // while (n > 0) { for (int i = 0; i < input.length; i++) { int parent = input[i]; if (!visites[i]) { if (parent == -2) { ++graphNum; graphs.add(graphNum - 1, new Graph<Integer>(i)); graphMap[i] = graphNum; visites[i] = true; --n; } else { int graphNumber = graphMap[parent] - 1; if (graphNumber >= 0) { Graph<Integer> graph = graphs.get(graphNumber); graph.add(i, parent); graphMap[i] = graphNumber + 1; visites[i] = true; --n; } } } } } /* * for (int i = 0; i < input.length; i++) { int parent = input[i]; if * (parent != -2) { int graphNumber = graphMap[parent] - 1; if * (graphNumber >= 0) { Graph<Integer> graph = graphs.get(graphNumber); * graph.add(i, parent); * * graphMap[i] = graphNumber + 1; } } } */ // answer int answer = 0; for (Graph<Integer> graph : graphs) answer = Math.max(answer, graph.getDeep()); ++answer; System.out.println(answer); } } class Graph<T> { private Map<T, List<T>> model = new HashMap<T, List<T>>(); private T root; public Graph() { } public Graph(T root) { this.root = root; model.put(root, new LinkedList<T>()); } public void add(T val, T parent) { if (model.size() == 0) root = val; if (parent != null) { List<T> children = model.get(parent); children.add(val); } model.put(val, new LinkedList<T>()); } public int getDeep() { return getDeep(root); } private int getDeep(T node) { int retDeep = 0; List<T> children = model.get(node); if (children.size() > 0) { for (T child : children) { int deep = getDeep(child); retDeep = Math.max(retDeep, deep); } return ++retDeep; } else { return retDeep; } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
fad6b6ddb1533192b8b35423d755661f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); int max = 1; int[] p = new int[n]; int[] c = new int[n]; Arrays.fill(c, 0); for(int k = 0; k < n; k++){ p[k] = r.nextInt(); if(p[k] != -1)p[k]--; } for(int i = 0; i < n; i++){ if(p[i] == -1)c[i] = 1; else{ int curr = i; int cnt = 1; while(p[curr] != -1){ cnt++; curr = p[curr]; } c[i] = cnt; max = Math.max(cnt, max); } } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
7436593958983dea22de7a80a319614d
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class Party { public static void main(String args[]) { final int MAXN = 2005; Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] p = new int[MAXN]; for (int i = 1; i <= n; i++) p[i] = scanner.nextInt(); int res = 0; for (int i = 1; i <= n; i++) { int count = 0; int u = i; while (u != -1) { u = p[u]; count++; } res = Math.max(res, count); } System.out.println(res); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
039b53b0f66f7c2f5059e350fce0f0c9
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class A115 { HashSet<Integer> visited; int maxDepth; public void init() { visited = new HashSet<Integer>(); maxDepth = 0; } public int getMaxDepth() { return maxDepth; } public void DFS(boolean a[][], int i, int depth) { maxDepth = Math.max(depth, maxDepth); visited.add(i); for (int j = 0; j < a[i].length; j++) { if (!visited.contains(j) && a[i][j]) DFS(a, j, depth + 1); } } public static void main(String args[]) { A115 obj = new A115(); obj.init(); Scanner in = new Scanner(System.in); int n = in.nextInt(); boolean graph[][] = new boolean[n + 1][n + 1]; for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (p == -1) graph[0][i] = true; else graph[p][i] = true; } obj.DFS(graph, 0, 0); System.out.println(obj.getMaxDepth()); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
99a05415037b1f0aece9a079ea0b9cac
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class F { static int best; static int n; static boolean[][] adj; static int[] m ; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n =sc.nextInt(); adj = new boolean[n][n]; best =0; m = new int[n]; Arrays.fill(m, -1); for(int a=0;a<n;a++){ int y = sc.nextInt()-1; if(y==-2)continue; adj[a][y]=true; } for(int a=0;a<n;a++){ best = Math.max(best, DFS(a)); } System.out.println(best+1); } private static int DFS(int b) { if(m[b]!=-1)return m[b]; for(int a=0;a<n;a++)if(adj[b][a])return m[b]=DFS(a)+1; return 0; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
447800e6256e1cff7de84adee0472707
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.awt.Point; public class Main { public static void main(String [] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); Point array[]=new Point[n+1]; for(int i=0;i<array.length;i++)array[i]=new Point(0,0); for(int i=1;i<=n;i++){ array[i]=new Point(i,in.nextInt()); } int max=-1; for(int i=1;i<array.length;i++){ int temp=array[i].y; int ans=1; while(temp!=-1){ ans++; temp=array[temp].y; } max=Math.max(ans,max); } System.out.print(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
1dd2fc38335aa10989040b25470c5692
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Party { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] employees = new int[n]; boolean[] b = new boolean[n]; Arrays.fill(b, false); for (int i = 0; i < n; i++){ employees[i] = in.nextInt() - 1; } int j; int maxChainLength = 0; for (int i = 0; i < n; i++){ if (!b[i]){ int chainLength = 1; j = i; while (employees[j] > -1){ j = employees[j]; chainLength++; b[j] = true; } maxChainLength = Math.max(maxChainLength, chainLength); } } System.out.println(maxChainLength); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
9f1b883845804559a34f999cc0224b4a
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Scanner in; static int next() throws Exception {return in.nextInt();} static PrintWriter out; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(); int[] p = new int[n]; for (int i = 0; i < n; i++) p[i] = next() - 1; int max = 0; for (int i = 0; i < n; i++) { int x = i; int count = 0; while (x >= 0) { x = p[x]; count++; } max = Math.max(max, count); } out.println(max); out.close(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
0241f265f34aa24964ca2e2b1a02346d
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int people = in.nextInt(); boolean[][] connected = new boolean[people][people]; LinkedList<Integer> q = new LinkedList<Integer>(); int[] levels = new int[people]; for(int i=0;i<people;++i) { int manager = in.nextInt(); if (manager != -1) { connected[manager-1][i] = true; } else { levels[i] = 1; q.offer(i); } } int ans = 1; while(!q.isEmpty()) { int cur = q.poll(); for(int i=0;i<people;++i) { if (connected[cur][i]) { ans = Math.max(ans, levels[cur]+1); levels[i] = levels[cur]+1; q.offer(i); } } } System.out.println(ans); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
a80f64b344d9c335b6ab493e21ca9e90
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = scanner.nextInt(); int[] manager = new int[n + 1]; for (int i = 1; i <= n; i++) { manager[i] = scanner.nextInt(); } int height = 1; for (int i = 1; i <= n; i++) { int count = 0; int father = i; while (father != -1) { father = manager[father]; count++; } height = Math.max(height, count); } System.out.println(height); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
25fd9b2c929c23093533703d2b37d462
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class C116 { static int n, manager[], id[], count; public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); n = in.nextInt(); manager = new int[n]; for (int i = 0; i < n; i++) manager[i] = in.nextInt() - 1; int max = -1; for (int i = 0; i < n; i++) max = Math.max(max, getMaxDepth(i)); System.out.println(max); } static int getMaxDepth(int i) { if (manager[i] == -2) return 1; return getMaxDepth(manager[i]) + 1; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
b6bff5cac2d06d3db18abecb83240c97
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(); int[] data = new int[n]; for(int i = 0; i<n; i++) data[i] = input.nextInt()-1; int res = 1; for(int i = 0; i<n; i++) { int at = 0, cur = i; while(cur != -2) { at++; cur = data[cur]; } res = Math.max(res, at); } out.println(res); out.close(); } static class Soldier implements Comparable<Soldier> { int b, i; public Soldier(int bb, int ii) { b = bb; i = ii; } @Override public int compareTo(Soldier that) { // TODO Auto-generated method stub return that.b - this.b; } } public 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 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
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
97bcadcb2b55ccbf1ca2932abe0be6b1
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Main implements Runnable { List<Integer>[] adj; boolean[] visited; int maxd(int from) { visited[from] = true; int ans = 1; for(int to : adj[from]) { if (!visited[to]) ans = Math.max(ans, maxd(to) + 1); } return ans; } public void solve() throws IOException { int n = nextInt(); int[] p = new int[n]; adj = new List[n]; for(int i = 0; i < n; ++i) { adj[i] = new ArrayList<Integer>(); } visited = new boolean[n]; for(int i = 0; i < n; ++i) { p[i] = nextInt(); if (p[i] != -1) { adj[i].add(p[i] - 1); adj[p[i] - 1].add(i); } } int ans = 0; for(int i = 0; i < n; ++i) if (p[i] == -1 && !visited[i]) { ans = Math.max(ans, maxd(i)); } pw.println(ans); } static final String filename = "A"; static final boolean fromConsole = true; public void run() { try { if (!fromConsole) { in = new BufferedReader(new FileReader(filename + ".in")); pw = new PrintWriter(filename + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } st = new StringTokenizer(""); long st = System.currentTimeMillis(); solve(); //pw.printf("\nWorking time: %d ms\n", System.currentTimeMillis() - st); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private StringTokenizer st; private BufferedReader in; private PrintWriter pw; boolean hasNext() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } return st.hasMoreTokens(); } String next() throws IOException { return hasNext() ? st.nextToken() : null; } int nextInt() throws IOException { return Integer.parseInt(next()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { new Thread(new Main()).start(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
66109d3ec01a1f148aa3c048f785ebc7
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int n = nextInt(); int[] ds = new int[n]; for (int i = 0; i < ds.length; i++) { ds[i] = nextInt() - 1; } int max = 0; for (int i = 0; i < ds.length; i++) { int res = 0; int cur = i; while(cur != -2) { cur = ds[cur]; res++; } max = Math.max(max, res); } System.out.println(max); } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = nextInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = nextLong(); } return res; } double[] readDoubleArray(int size) throws IOException { double[] res = new double[size]; for (int i = 0; i < size; i++) { res[i] = nextDouble(); } return res; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
5319527dcaa099a3be9973f01b9ad14b
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class A115 { static class guy { guy boss; int dist = -1; public guy() { boss = null; } public int getDist() { if (dist == -1) { if (boss == null) { dist = 1; } else dist = 1 + boss.getDist(); } return dist; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); guy[] g = new guy[n]; for (int x = 0; x < n; x++) { g[x] = new guy(); } for(int x = 0;x<n;x++) { int next = in.nextInt(); if(next==-1) continue; g[x].boss = g[next-1]; } int max = 0; for(int x =0;x<n;x++ ){ int k = g[x].getDist(); if(k>max) max = k; } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
953ec93a0b55c875c5eb2220225f9d0e
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class A { BufferedReader in; StringTokenizer str; PrintWriter out; String SK; String next() throws IOException { while ((str == null) || (!str.hasMoreTokens())) { SK = in.readLine(); if (SK == null) return null; str = new StringTokenizer(SK); } return str.nextToken(); }; int nextInt() throws IOException { return Integer.parseInt(next()); }; double nextDouble() throws IOException { return Double.parseDouble(next()); }; long nextLong() throws IOException { return Long.parseLong(next()); }; int a[]; int res[]; int max = 0; void upgr(int n) { if (res[n] != 0) return; if (a[n] == -2) res[n] = 1; else { upgr(a[n]); res[n] = 1 + res[a[n]]; } } void solve() throws IOException { int n = nextInt(); a = new int[n]; res = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() - 1; for (int i = 0; i < n; i++) upgr(i); for (int i = 0; i < n; i++) max = Math.max(max, res[i]); out.println(max); }; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A().run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
19c028e55d4a8240466cd31d0a1e1edb
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class P1 { static class Scanner{ BufferedReader br=null; StringTokenizer tk=null; public Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException{ while(tk==null || !tk.hasMoreTokens()) tk=new StringTokenizer(br.readLine()); return tk.nextToken(); } public int nextInt() throws NumberFormatException, IOException{ return Integer.valueOf(next()); } public double nextDouble() throws NumberFormatException, IOException{ return Double.valueOf(next()); } } static class Man{ boolean visited; int altura; int vecino; public Man(int vec){ visited = false; altura = 1; vecino = vec; } } static Man[] array; static int dfs(int index){ if (array[index].visited) return array[index].altura; int altura = 1; if (array[index].vecino != -1) altura = dfs(array[index].vecino) + 1; array[index].visited = true; array[index].altura = altura; return altura; } public static void main(String args[]) throws NumberFormatException, IOException{ Scanner sc = new Scanner(); int N = sc.nextInt(); array = new Man[N + 1]; for(int i = 1; i <= N; i++) array[i] = new Man(sc.nextInt()); for(int i = 1; i <= N; i++) dfs(i); int ans = 0; for(int i = 1; i <= N; i++ ) ans = Math.max(ans, array[i].altura); System.out.println(ans); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
ee90e687d568bae1a06c0273dd1c9025
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class A{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int n; int[] p; void run(){ n=sc.nextInt(); p=new int[n]; for(int i=0; i<n; i++){ p[i]=sc.nextInt(); if(p[i]>0){ p[i]--; } } int ans=0; for(int i=0; i<n; i++){ int c=0; for(int v=i; v>=0; v=p[v]){ c++; } ans=max(ans, c); } println(ans+""); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ new A().run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
0c6431dddac116d9caac2e7ab26527fe
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; // Party // 2011/9/16 public class P115A{ Scanner sc=new Scanner(System.in); int n; int[] p; void run(){ n=sc.nextInt(); p=new int[n]; for(int i=0; i<n; i++){ p[i]=sc.nextInt(); if(p[i]>0){ p[i]--; } } int ans=0; for(int i=0; i<n; i++){ int c=0; for(int v=i; v>=0; v=p[v]){ c++; } ans=max(ans, c); } println(ans+""); } void println(String s){ System.out.println(s); } public static void main(String[] args){ new P115A().run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
f9a8693d46895457c8c866ed3b22957d
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import javax.swing.border.EmptyBorder; public class CodeD { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } } static class Empleado { Empleado jefe; ArrayList <Empleado> subOrdinados = new ArrayList <Empleado> (); int mayorAltura() { int resultado = 1; for(Empleado e : subOrdinados) resultado = Math.max(resultado, 1 + e.mayorAltura()); return resultado; } } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); Empleado[] empleados = new Empleado[n]; for(int i = 0; i < n; i++) empleados[i] = new Empleado(); for(int i = 0; i < n; i++) { int val = sc.nextInt() - 1; if(val != -2) { empleados[i].jefe = empleados[val]; empleados[val].subOrdinados.add(empleados[i]); } } int max = 0; for(int i = 0; i < n; i++) { if(empleados[i].jefe == null) max = Math.max(max, empleados[i].mayorAltura()); } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
928974aa7d655628f4484907d84843aa
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable{ private static String filename; public static void main(String[] args){ if (args.length>0 && args[0].equals("f")) filename = "input.txt"; else filename = ""; new Thread(new Main()).start(); } private static void debug(Object ... str){ for (Object s : str) System.out.print(s + ", "); System.out.println(); } int height = 0; void dfs(int v, int h){ was[v] = true; for (int u : g[v]) if (!was[u]) dfs(u, h + 1); height = Math.max(h, height); } boolean[] was; ArrayList<Integer>[] g; public void run(){ try{ MyScanner in; Locale.setDefault(Locale.US); if (filename.length()>0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); was = new boolean[n]; g = new ArrayList[n]; ArrayList<Integer> parents = new ArrayList(); for (int i = 0; i<n; i++) g[i] = new ArrayList<Integer>(); for (int i = 0; i<n; i++){ int pi = in.nextInt(); if (pi < 0) parents.add(i); else g[pi - 1].add(i); } for (int ps : parents) dfs(ps, 0); out.println(height + 1); out.close(); in.close(); }catch(Exception e){ e.printStackTrace(); } } } class MyScanner{ BufferedReader in; StringTokenizer st; MyScanner(String file){ try{ in = new BufferedReader(new FileReader(new File(file))); }catch(Exception e){ e.printStackTrace(); } } MyScanner(InputStream inp){ try{ in = new BufferedReader(new InputStreamReader(inp)); }catch (Exception e){ e.printStackTrace(); } } void skipLine(){ st = null; } boolean hasMoreTokens(){ String s = null; try{ while ((st==null || !st.hasMoreTokens())&& (s=in.readLine()) != null) st = new StringTokenizer(s); if ((st==null || !st.hasMoreTokens())&& s==null) return false; }catch(IOException e){ e.printStackTrace(); } return true; } String nextToken(){ if (hasMoreTokens()){ return st.nextToken(); } return null; } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong(){ return Long.parseLong(nextToken()); } double nextDouble(){ return Double.parseDouble(nextToken()); } String nextString(){ return nextToken(); } void close(){ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
150df0dcf1428084254991a61fd27493
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; public class Prob115A { public static void main( String[] Args ) { Scanner scan = new Scanner( System.in ); int employees = scan.nextInt(); int[] rank = new int[employees]; ArrayList<Integer>[] fol = new ArrayList[employees]; Stack<Integer> ranks = new Stack<Integer>(); for ( int x = 0; x < employees; x++ ) fol[x] = new ArrayList<Integer>(); for ( int x = 0; x < employees; x++ ) { int boss = scan.nextInt() - 1; if ( boss != -2 ) { fol[boss].add( x ); } else { ranks.add( x ); rank[x] = 1; } } int maxLength = 0; while ( !ranks.isEmpty() ) { int cur = ranks.pop(); if ( fol[cur].size() == 0 ) { maxLength = Math.max( maxLength, rank[cur] ); } else { for ( int i = 0; i < fol[cur].size(); i++ ) { ranks.add( fol[cur].get( i ) ); rank[fol[cur].get( i )] = rank[cur] + 1; } } } System.out.println( maxLength ); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
2635415bec17638eb9132c8daf34dedc
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class AAA { boolean[] vis; int[] mng; boolean[] isM; public static void main(String[] args) { new AAA().go(); } public void go() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); mng = new int[n]; isM = new boolean[n]; for (int i = 0; i < n; ++i) { mng[i] = sc.nextInt(); if (mng[i] != -1) { --mng[i]; isM[mng[i]] = true; } } int rMax = -1; for (int i = 0; i < n; ++i) { if (!isM[i]) { int r = 0; int j = i; while (true) { if (j == -1) break; ++r; j = mng[j]; } rMax = Math.max(rMax, r); } } System.out.println(rMax); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
986336b386616d0692935be8e57827ec
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Main(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution void solve() throws IOException { int n=readInt(); int[] a=new int[n+1]; for(int i=0;i<n;i++) a[i+1]=readInt(); int tec,max=1,j; for(int i=1;i<=n;i++){ tec=1; j=i; while(a[j]!=-1){ j=a[j]; tec++; } if(tec>max) max=tec; } out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
3755ab42af4f31feb5fb06c1247e4135
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class A87 { int fa[] = new int[5000]; public int find(int x,int now){ if (fa[x]==-1) return now; return find(fa[x],now+1); } public A87(Scanner in){ int n = in.nextInt(); for(int i = 1;i<=n;i++){ fa[i]=in.nextInt(); } int max = 0; for(int i =1;i<=n;i++){ max = Math.max(max,find(i,1)); } System.out.println(max); } public static void main(String args[]){ new A87(new Scanner(System.in)); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
4be40d1ce1df08f09f690bf8cf5f0b4f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] agrs) { new A().run(); } public void run() { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); n = reader.nextInt(); ne = 0; LE = new int[n + 1]; Arrays.fill(LE, -1); E = new Edge[5 * n]; din = new int[n + 1]; Arrays.fill(din, 0); for (int i = 1; i <= n; i++) { int direct = reader.nextInt(); if (direct != -1) { addEdge(direct, i); din[i]++; } } int ans = -1; for (int u = 1; u <= n; u++) { if (din[u] == 0) { int[] d = bfs(u); for (int i = 1; i <= n; i++) { if (d[i] < Integer.MAX_VALUE && ans < d[i] + 1) { ans = d[i] + 1; } } } } writer.println(ans); writer.close(); } public int[] bfs(int x) { int[] d = new int[n + 1]; Arrays.fill(d, Integer.MAX_VALUE); d[x] = 0; Queue <Integer> queue = new LinkedList <Integer> (); queue.add(x); while (!queue.isEmpty()) { int u = queue.remove(); for (int ID = LE[u]; ID != -1; ID = E[ID].nextID) { int v = E[ID].to; if (d[v] > d[u] + 1) { d[v] = d[u] + 1; queue.add(v); } } } return d; } public int n, ne; public int[] LE, din; public Edge[] E; public void addEdge(int u, int v) { E[ne] = new Edge(v, LE[u]); LE[u] = ne++; } public class Edge { public int to, nextID; public Edge(int to, int nextID) { this.to = to; this.nextID = nextID; } } public class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { tokenizer = null; try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) {} } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { if (tokenizer != null && tokenizer.hasMoreTokens()) { return true; } try { reader.mark(Integer.MAX_VALUE); if (reader.readLine() == null) { return false; } reader.reset(); } catch (IOException e) {} return true; } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
d1311fe2590c9c3f85e2beb5f8b6273b
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Party { public static boolean conec[][]; public static boolean seen[]; public static int n = 0; public static int ans = 0; public static int num = 0; public static int color[]; public static int parent[]; public static int distance[]; public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = sc.nextInt(); int i = 0, j = 0, k = 0; conec = new boolean[n][n]; seen = new boolean[n]; color = new int[n]; distance = new int[n]; parent = new int[n]; int ga[] = new int[n]; for (i = 0; i < n; ++i) { int tem = sc.nextInt(); ga[i] = tem; if (tem != -1) { // conec[i][tem - 1] = true; conec[tem - 1][i] = true; } } int now = 0; for (j = 0; j < n; ++j) { if (ga[j] == -1) { bfs(j); //System.out.println(Arrays.toString(distance)); for (i = 0; i < n; ++i) { if (now < distance[i]) { now = distance[i]; } } seen = new boolean[n]; color = new int[n]; distance = new int[n]; parent = new int[n]; } } System.out.println(now + 1); } public void bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); color[s] = 1; distance[s] = 0; parent[s] = -1; q.add(s); while (!q.isEmpty()) { int u = q.poll(); for (int v = 0; v < n; ++v) { if (color[v] == 0 && conec[u][v]) { color[v] = 1; distance[v] = distance[u] + 1; parent[v] = u; q.add(v); } } color[u] = 2; } } public static void main(String[] args) throws IOException { new Party().solve(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
3975a65fe840345053dbe74179457022
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class ADiv1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] M = new int[n]; for (int i = 0; i < n; i++) M[i] = in.nextInt() - 1; int ans = 0; for (int i = 0; i < n; i++) { int temp = M[i]; int cnt = 1; while (temp != -2) { cnt++; temp = M[temp]; } ans = Math.max(ans, cnt); } System.out.println(ans); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
7df099f3f3ed5c87d56bf5cd61cac47f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = s.nextInt(); } int max = 0; for(int i = 0; i < n; ++i){ max = Math.max(max, f(i, 1)); } System.out.println(max); } static int[] a; static int f(int i, int d){ if(a[i] < 0){ return d; }else{ return f(a[i]-1, d + 1); } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
d87fb8cfcb54bcce9ea04ea3074d13dd
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class CodeforcesBetaRound87Div1_A { static int count(int[] p, int i) { int c = 1; while (p[i] != -1) { i = p[i]; c++; } return c; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] parent = new int[n+1]; for (int i = 1; i <= n; i++) parent[i] = scan.nextInt(); int max=1; for (int i = 1; i <= n; i++) max = Math.max(max, count(parent, i)); System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
7ae826d5b1abf0e5e7c5a73f1a3d876c
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Trung Pham */ public class A { public static int mod = (int) (1e6 + 3); //public static String[] ps = {"rock", "paper", "scissors"}; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); boolean[][] map = new boolean[n][n]; boolean []root = new boolean[n]; for (int i = 0; i < n; i++) { int a = in.nextInt(); if (a != -1) { root[i] = true; map[a - 1][i] = true; } } int max = 1; boolean[] mark = new boolean[n]; int[] level = new int[n]; for (int i = 0; i < n; i++) { if (!mark[i] && !root[i]) { // System.out.println(i); ArrayList<Integer> list = new ArrayList(); list.add(i); mark[i] = true; level[i] = 1; while (!list.isEmpty()) { int node = list.remove(0); for (int j = 0; j < n; j++) { if (!mark[j] && map[node][j]) { mark[j] = true; level[j] = level[node] + 1; max = Math.max(level[j],max); list.add(j); } } } } } out.println(max); out.close(); } static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return (val * val) % mod; } else { return val * (val * a % mod) % mod; } } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } static Point add(Point a, Point b) { return new Point(a.x + b.x, a.y + b.y); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point: " + x + " " + y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
3b9a948cb1c692de1b1fef1a61fc1df6
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] argv) throws IOException{ new Main().run(argv); } PrintWriter pw; Scanner sc; public void run(String[] argv) throws IOException{ boolean oj = !(argv.length>0 && argv[0].equals("ulugbek"));//System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); oj = true; Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); sc = new Scanner(reader); pw = new PrintWriter(writer); solve(); pw.close(); } public void solve(){ int n = sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt()-1; } int ans=0; for(int i=0;i<n;i++){ int ans2=1; int cur = i; while(arr[cur]>-1){ ans2++; cur = arr[cur]; } if(ans2>ans) ans = ans2; } pw.println(ans); } public class A{ public A parent; public boolean used; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
65fa1cc800a2b49de00e383fe34639e7
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Saransh */ import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { /** * @param args the command line arguments */ static int arr[]; static boolean can[][]; static boolean marked[]; public static void main(String[] args) { // TODO code application logic here try { Parserdoubt pd=new Parserdoubt(System.in); PrintWriter pw=new PrintWriter(System.out); int n=pd.nextInt(); arr=new int[n]; for(int i=0;i<n;i++) arr[i]=pd.nextInt()-1; int c=-1; for(int i=0;i<n;i++) c=Math.max(c,superior(i)); pw.print(c); pw.flush(); } catch(Exception e) { e.printStackTrace(); } } public static void dfs(int a) { if(marked[a])return; marked[a]=true; for(int i=0;i<marked.length;i++) { if(!marked[i]&&can[i][a]) dfs(i); } } public static int superior(int i) { if(arr[i]==-2) return 1; return 1+superior(arr[i]); } } class Parserdoubt { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
d92c1269e1f0bd39eca25702ec8ad7bd
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.IOException; import java.util.Scanner; public class ProblemC { public static int[] memo; public static int[] manager; public static int[][] children; public static int length(int idx, int n) { if (memo[idx] > 0) { return memo[idx]; } int max = 1; for (int i = 0 ; i < n ; i++) { if (children[idx][i] > 0) { max = Math.max(max, length(i, n) + 1); } } memo[idx] = max; return max; } public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); int n = Integer.valueOf(s.nextLine()); memo = new int[n]; manager = new int[n]; children = new int[n][n]; for (int k = 0 ; k < n ; k++) { manager[k] = Integer.valueOf(s.nextLine()); if (manager[k] >= 1) { manager[k] -= 1; children[manager[k]][k] = 1; } } int max = 0; for (int k = 0 ; k < n ; k++) { if (manager[k] == -1) { max = Math.max(max, length(k, n)); } } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
cae0f4a16b6683701cf65e56abe31b14
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class test { static int max=0; static int[] level=null; static int[] head=null; static int getLevel(int m) { if(level[m]!=0) return level[m]; if(head[m]==-1) level[m]=1; else level[m]=1+getLevel(head[m]); max=Math.max(max,level[m]); return level[m]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); level=new int[n]; head=new int[n]; for(int i=0;i<n;i++) { head[i]=in.nextInt(); if(head[i]!=-1) head[i]--; } for(int i=0;i<n;i++) getLevel(i); System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
7a5a76b2f821242ffa841a2a9e4f7a4e
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] p = new int[n+1]; int[] l = new int[n+1]; for (int j = 0; j < n; ++j) p[j+1] = s.nextInt(); for (int j = 1; j <= n; ++j) l[j] = -1; for (int j = 1; j <= n; ++j) { if (l[j] != -1) continue; ArrayList<Integer> path = new ArrayList<Integer>(); int k = j; while (p[k] != -1 && l[k] == -1) { path.add(k); k = p[k]; } int size = path.size() + ((l[k] == -1) ? 0 : l[k]); for (int v : path) { l[v] = size--; } } int c = 0; for (int j = 1; j <= n; ++j) if (c < l[j]) c = l[j]; System.out.println(c+1); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
0f414c9687f5fd6647f2a6ceab4ed52f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; public class Main implements Runnable { StreamTokenizer in; BufferedReader reader; PrintWriter out; StringTokenizer tok; boolean timus = System.getProperty("ONLINE_JUDGE")!=null; boolean codeforces = true; final double eps = 1e-9; public static void main(String[] args) throws Exception { new Thread(new Main()).start(); } @Override public void run() { try { if (codeforces) { reader = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(reader); out= new PrintWriter (new OutputStreamWriter(System.out)); tok = new StringTokenizer(""); solve(); out.flush(); } else if (!timus) { long begMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long t1 = System.currentTimeMillis(); reader = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(reader); out= new PrintWriter (new OutputStreamWriter(System.out)); tok = new StringTokenizer(""); solve(); long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); out.flush(); long t2 = System.currentTimeMillis(); System.out.println("Time:"+(t2-t1)); System.out.println("Memory:"+(endMem-begMem)); System.out.println("Total memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } else { reader = new BufferedReader(new FileReader("input.txt")); in = new StreamTokenizer(reader); out= new PrintWriter (new FileWriter("output.txt")); tok = new StringTokenizer(""); solve(); out.flush(); out.close(); } } catch (Exception ex) { System.out.println("fail"); System.exit(1); } } public class Chess { String coord; public Chess(String s){ this.coord=s; } public int toInteger(char s) { if (s=='a'||s=='A') return 1; else if (s=='b'||s=='B') return 2; else if (s=='c'||s=='C') return 3; else if (s=='d'||s=='D') return 4; else if (s=='e'||s=='E') return 5; else if (s=='f'||s=='F') return 6; else if (s=='g'||s=='G') return 7; else if (s=='h'||s=='H') return 8; else return -1; } public String toString(int s) { if (s==1) return "a"; else if (s==2) return "b"; else if (s==3) return "c"; else if (s==4) return "d"; else if (s==5) return "e"; else if (s==6) return "f"; else if (s==7) return "g"; else if (s==8) return "h"; else return "0"; } public pair getPair() { String j=""; j+=coord.charAt(1); pair p = new pair(toInteger(coord.charAt(0)),Integer.parseInt(j)); if (p.x!=-1) return p; else return new pair(0,0); } public String returnPair(pair p) { return toString(p.x)+p.y; } } public int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } public String next() throws Exception { in.nextToken(); return in.sval; } public String nextLine() throws Exception { return reader.readLine(); } public String nextString() throws Exception { while (!tok.hasMoreTokens()) tok = new StringTokenizer(reader.readLine()); return tok.nextToken(); } public long nextLong() throws Exception { return Long.parseLong(nextString()); } public double nextDouble() throws Exception { in.nextToken(); return in.nval; } public class pair { int x; int y; public pair(int x, int y) { this.x=x; this.y=y; } } public int gcd(int a, int b) { if (a== 0||b==0) return 1; if (a<b) { int c=b; b=a; a=c; } while (a%b!=0) { a =a%b; if (a<b) { int c=b; b=a; a=c; } } return b; } public int pow(int a, int n) { if (n==0) return 1; int k=n, b=1, c=a; while (k!=0) { if (k%2==0) { k/=2; c*=c; } else { k--; b*=c; } } return b; } public int lcm(int a, int b) { return a*b/gcd(a,b); } public class pairs implements Comparable<pairs> { int x; int y; public pairs(int x, int y) { this.x=x; this.y=y; } @Override public int compareTo(pairs obj) { if (this.x<((pairs)obj).x) return 1; else if (this.x==(obj).x&&this.y<(obj).y) return 1; else if (this.x==(obj).x&&this.y==(obj).y)return 0; else return -1; } } public class Graf { int [][] a; int [] colors; ArrayList <String> points = new ArrayList<String>(); LinkedList <Integer> queue = new LinkedList <Integer>(); boolean [] used; boolean cycle; int numberOfCycle; public Graf(int [][]a,String s[]) { this.a=new int [s.length][s.length]; this.a=a; this.colors=new int [s.length]; this.used=new boolean[s.length]; for (int i=0; i<s.length;i++) { this.colors[i]=0; this.points.add(s[i]); } Arrays.fill(this.used, false); } public void bfs(int i) { this.queue.add(i); while (!this.queue.isEmpty()) { i = this.queue.pop(); this.used[i]=true; for (int j=0; j<this.points.size();j++) { if (this.a[i][j]==1&&!this.queue.contains(j)&&!this.used[j]) { this.a[i][j]=0; this.a[j][i]=0; this.queue.addLast(j); } } } } public void dfs(int i,int k) { max = max(max,k); for (int j=0; j<this.colors.length;j++) { if (this.a[i][j]==1) { this.used[i]=true; this.used[j]=true; dfs(j,k+1); } } } } public class Time { int h; int min; int sec; public Time(String s) { String [] st = s.split(":"); this.h =Integer.parseInt(st[0]); this.min =Integer.parseInt(st[1]); this.sec =(st[2]!=null)? Integer.parseInt(st[2]):0; } public String toString(int a) { String h = Integer.toString(this.h); String min = Integer.toString(this.min); String sec = Integer.toString(this.sec); if (h.length()==1) { h='0'+h; } if (min.length()==1) { min='0'+min; } if (sec.length()==1) { sec='0'+sec; } if (a==5) { return h+":"+min; } else { return h+":"+min+":"+sec; } } public void to12HoursFormat () { h%=12; } public void add (int h,int min,int s) { this.sec+=s; if (this.sec>=60) { this.min++; this.sec%=60; } this.min+=min; if (this.min>=60) { this.h++; this.min%=60; } this.h+=h; if (this.h>=24) { this.h%=24; } } } public int[] findPrimes(int x) { boolean[] erat = new boolean[x-1]; List<Integer> t = new ArrayList<Integer>(); int l=0, j=0; for (int i=2;i<x; i++) { if (erat[i-2]) continue; t.add(i); l++; j=i*2; while (j<x) { erat[j-2]=true; j+=i; } } int[] primes = new int[l]; Iterator<Integer> iterator = t.iterator(); for (int i = 0; iterator.hasNext(); i++) { primes[i]=iterator.next().intValue(); } return primes; } public double dist(pair a,pair b) { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } int max=1; int mas[] = new int [2500] ; int dfs(int x,int r) { r++; if(mas[x]==-1) return r ; return dfs(mas[x],r); } public void solve() throws Exception { int n,i,t,max=0; n=nextInt(); for(i=1;i<=n;i++) mas[i]=nextInt(); for(i=1;i<=n;i++) {t=dfs(i,0); if(t>max) max=t;}; out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
39d63b607d83000ead2a4759f00b2aa6
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
//package round87; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.Scanner; public class A { Scanner in; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] p = new int[n]; for(int i = 0;i < n;i++)p[i] = ni()-1; DJSet ds = new DJSet(n); for(int i = 0;i < n;i++){ if(p[i] != -2){ ds.union(i, p[i]); } } int[] imap = new int[n]; int[] map = new int[n]; int max = 0; for(int i = 0;i < n;i++){ if(ds.upper[i] < 0){ int z = 0; for(int j = 0;j < n;j++){ if(ds.root(j) == i){ map[z] = j; imap[j] = z++; } } int[] lp = new int[-ds.upper[i]]; int root = -1; for(int j = 0;j < z;j++){ lp[j] = p[map[j]] == -2 ? -1 : imap[p[map[j]]]; if(p[map[j]] == -2)root = j; } int[][] ch = parentToChildren(lp); int[] d = new int[z]; Queue<Integer> q = new ArrayDeque<Integer>(); q.add(root); d[root] = 1; while(q.size() > 0){ int cur = q.poll(); max = Math.max(max, d[cur]); for(int c : ch[cur]){ d[c] = d[cur] + 1; q.add(c); } } } } out.println(max); } public class DJSet { public int[] upper; public DJSet(int n){ upper = new int[n]; Arrays.fill(upper, -1);} public int root(int x){ return upper[x] < 0 ? x : (upper[x] = root(upper[x]));} public boolean equiv(int x, int y){ return root(x) == root(y);} public void union(int x, int y){ x = root(x);y = root(y);if(x != y) { if(upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x;}} public int count(){ int ct = 0; for(int i = 0;i < upper.length;i++){ if(upper[i] < 0)ct++; } return ct; }} public static int[][] parentToChildren(int[] parent) { int n = parent.length; int[] ct = new int[n]; for(int i = 0;i < n;i++){ if(parent[i] >= 0){ ct[parent[i]]++; } } int[][] ret = new int[n][]; for(int i = 0;i < n;i++){ ret[i] = new int[ct[i]]; } for(int i = 0;i < n;i++){ if(parent[i] >= 0){ ret[parent[i]][--ct[parent[i]]] = i; } } return ret; } void run() throws Exception { in = oj ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
a7f1b3dc40bfdb8ca92a7b89a378e70f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Stack; import java.util.StringTokenizer; public class Solution { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solve() throws IOException { int n = nextInt(); int a[] = new int[n + 1]; int d[] = new int[n + 1]; Stack<Integer> stack = new Stack<Integer>(); for(int i = 1; i <= n; i++) { a[i] = nextInt(); if(a[i] == -1) { stack.add(i); d[i] = 1; } } while(!stack.isEmpty()) { int tmp = stack.pop(); for(int i = 1; i <= n; i++) { if(a[i] == tmp) { stack.push(i); d[i] = d[a[i]] + 1; } } } int max = 0; for(int i = 1; i <= n; i++) { if(max < d[i]) { max = d[i]; } } System.out.println(max); } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.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()); } public static void main(String args[]) throws IOException { new Solution().solve(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
c973d259ccaa2c51ffc415c9f7f5f853
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class P115A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int[] link = new int[N+1]; for (int n = 1; n <= N; ++n) link[n] = in.nextInt(); int max = 1; for (int n = 1; n <= N; ++n) { int depth = 1; int i = n; while (link[i] != -1) { ++depth; i = link[i]; } max = Math.max(max, depth); } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
a432cf97a29f252e0f8d6aeb26969069
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.awt.Point; import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class A { static int[] level,parent; public static void main(String[] args) { Scanner sc=new Scanner(System.in); parent=new int[sc.nextInt()]; int[] taken=new int[parent.length]; for(int i=0;i<parent.length;i++) { parent[i]=sc.nextInt()-1; if(parent[i]>=0) taken[parent[i]]=1; } level=new int[parent.length]; LinkedList<Point> a=new LinkedList<Point>(); for(int i=0;i<taken.length;i++) if(taken[i]==0) a.add(new Point(i,1)); while(!a.isEmpty()) { Point tmp=a.remove(); level[tmp.x]=Math.max(level[tmp.x], tmp.y); if(parent[tmp.x]>=0) a.add(new Point(parent[tmp.x],level[tmp.x]+1)); } Arrays.sort(level); System.out.println(level[level.length-1]); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
95ddd8a306b247c146bfc4d73f10a3f1
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; import java.util.List; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Johan Sannemo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { int n; List<Integer>[] childs; boolean [] root; public int recurse(int idx){ int max = 0; for(Integer i : childs[idx]){ max = Math.max(recurse(i), max); } return max+1; } public void solve(int testNumber, Scanner in, PrintWriter out) { n = in.nextInt(); childs = new LinkedList[n]; root = new boolean[n]; for(int i = 0; i<n; i++) childs[i] = new LinkedList<Integer>(); for(int i = 0; i<n; i++){ int boss = in.nextInt(); if(boss != -1){ boss--; childs[boss].add(i); } else { root[i] = true; } } int max = 0; for(int i = 0; i<n; i++){ if(root[i]){ max = Math.max(recurse(i), max); } } out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
a9a0e906f5861f3509af656b9adc7a59
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Q116C implements Runnable { private void solve() throws IOException { int n = nextInt(); Per[] pers = new Per[n]; for (int i = 0; i < n; i++) { if (pers[i] == null) pers[i] = new Per(); int parent = nextInt()-1; if (parent >=0) { if (pers[parent] == null) pers[parent] = new Per(); pers[parent].podch.add(pers[i]); } } int max = 0; for (int i = 0; i < n; i++) { max = Math.max(max, len(pers[i])); } //max = Math.min(max, 3); writer.print(max); } private int len(Per per) { int max = 0; for (Per p : per.podch) { max = Math.max(max, len(p)); } return 1 + max; } private static class Per { List<Per> podch = new ArrayList<Per>(); } public static void main(String[] args) { new Q116C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new BufferedReader(new InputStreamReader(System.in)) : new BufferedReader(new FileReader(new File("input.txt"))); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
7c4cbad46f4c8a0e7ce47b2fd01008e9
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; public class CodeForce { public int g(Map<Integer, List<Integer>> g, int v, int c) { int ret = c; List<Integer> li = g.get(v); for(int i = 0; i < li.size(); i++) ret = Math.max(ret, g(g, li.get(i), c + 1)); return ret; } private void solve() throws IOException { int n = nextInt(); List<Integer> roots = new LinkedList<Integer>(); Map<Integer, List<Integer>> g = new HashMap<Integer, List<Integer>>(); for(int i = 1; i <= n; i++) g.put(i, new LinkedList<Integer>()); for(int i = 1; i <= n; i++) { int p = nextInt(); if(p == -1) { roots.add(i); continue; } List<Integer> li = g.get(p); li.add(i); } int ret = 0; for(int i = 0; i < roots.size(); i++) ret = Math.max(ret, g(g, roots.get(i), 1)); System.out.println(ret); } public static void main(String[] args) { new CodeForce().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(new FileOutputStream(new File("output.txt"))); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
417ddf860874a9210118c2c02c875874
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Party{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int n = reader.nextInt(); int[][] g = new int[n][n]; for(int i = 0; i < n; i++){ int p = reader.nextInt(); if(p>-1) g[p-1][i] = 1; } System.out.println(sort(g)); } public static int sort(int[][] g){ LinkedList<Integer> q = new LinkedList<Integer>(); int n = g.length; int[] in = new int[n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) in[i] += g[j][i]; int[] level = new int[n]; Arrays.fill(level, 0); for(int i = 0; i < n; i++) if(in[i] == 0) q.add(i); while(!q.isEmpty()){ int c = q.remove(); for(int i = 0; i < n; i++){ if(g[c][i] == 1){ in[i]--; if(in[i] == 0) q.add(i); level[i] = level[c] + 1; } } } //count unique levels boolean[] used = new boolean[n+1]; int cnt = 0; for(int i = 0; i < n; i++) if(!used[level[i]]){ cnt++; used[level[i]] = true; } return cnt; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
f5836826a060cdbf261e59e15dbeaea8
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author megaterik */ import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class c implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new c(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution void solve() throws IOException { int n = readInt(); int[] up = new int[n], h = new int[n]; for (int i = 0; i < n; i++) { up[i] = readInt() - 1; } for (int turn = 0; turn < n; turn++) { for (int i = 0; i < n; i++) { if (up[i] == -2) h[i] = 1; else h[i] = h[up[i]] + 1; } } int result = 0; for (int num : h) { result = Math.max(result, num); } out.println(result); out.flush(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
39139cfc175066024d3f18e8de9f8b0f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ String s; while (st==null || !st.hasMoreTokens()){ s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static String nextStr() throws IOException{ return nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static long nextLong() throws IOException{ return Long.parseLong(nextToken()); } static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } public static void main(String[] args) throws IOException{ int n = nextInt(), a[] = new int[n], b[] = new int[n]; for (int i=0; i<n; i++){ a[i] = nextInt()-1; if (a[i] != -2) b[a[i]] = 1; } int res = 1; for (int i=0; i<n; i++) if (b[i] == 0){ int p = i; int k = 0; while (p != -2){ p = a[p]; k++; } res = Math.max(res, k); } out.println(res); out.flush(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
b5ea18522b958cbf35ffc9ae07e692cc
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution115A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Solution115A().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } int DFS(int x, int[] boss){ if(x == -1) return 0; return DFS(boss[x], boss) + 1; } void solve() throws IOException{ int n = readInt(); int[] boss = new int[n]; for(int i = 0; i < n; i++){ boss[i] = readInt()-1; if(boss[i] == -2) boss[i] = -1; } int max = 0; for(int i = 0; i < n; i++){ int cur = DFS(i, boss); if(cur > max) max = cur; } out.println(max); } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
317cc1275f3150651e60fee434684022
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.InputStreamReader; import java.util.Scanner; public class B { public static Scanner in = new Scanner(new InputStreamReader(System.in)); static boolean[][] C = new boolean[2005][2005]; static int[] queue = new int[2005]; static int[] d = new int[2005]; public static void main(String[] args) { int n = in.nextInt(); int first=1; int last=0; for(int i=1; i<=n; i++){ int j = in.nextInt(); if (j!=-1) C[j][i]=true; else{ queue[++last]=i; //System.out.println("queue add: "+i); d[i]=1; } } while(first<=last){ int u = queue[first]; first++; for(int v=1; v<=n; v++) if (C[u][v] && d[v]==0){ d[v]=d[u]+1; queue[++last]=v; } } int result=0; for(int u=1; u<=n; u++) if (result<d[u]) result=d[u]; System.out.println(result); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
90750972396a5a60aeb933796f2c708d
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class A87 { int fa[] = new int[5000]; public int find(int x,int now){ if (fa[x]==-1) return now; return find(fa[x],now+1); } public A87(Scanner in){ int n = in.nextInt(); for(int i = 1;i<=n;i++){ fa[i]=in.nextInt(); } int max = 0; for(int i =1;i<=n;i++){ max = Math.max(max,find(i,1)); } System.out.println(max); } public static void main(String args[]){ new A87(new Scanner(System.in)); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
8edfda720deff00d19d68b8602304491
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/26/11 * Time: 10:53 PM * To change this template use File | Settings | File Templates. */ public class TaskA { int n; int[] p; int[] depth; int getDepth(int i) { if(depth[i] != -1) return depth[i]; if(p[i] == -1) return 1; return 1 + getDepth(p[i]); } void run(){ n = nextInt(); p = new int[n]; for(int i = 0; i < n; i++) { int x = nextInt(); if(x == -1) p[i] = -1; else p[i] = x - 1; } depth = new int[n]; Arrays.fill(depth, -1); for(int i = 0; i < n; i++) { depth[i] = getDepth(i); } int ans = 0; for(int x : depth)ans = Math.max(x, ans); System.out.println(ans); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskA().run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
9f33a8be5d0808e4d73459d7e8496b23
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class P115A { public static void main(String[] Args) { new P115A().solve(); } Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); void solve() { int n = si(), p[]=sai_(n), a= 0; for (int i = 1; i <= n; i++) { int boss = p[i], d=1; while(boss!=-1){ d++; boss = p[boss]; } a=Math.max(d, a); } System.out.println(a); } static int toi(Object s) { return Integer.parseInt(s.toString()); } // ----------------------- Library ------------------------ static int[] dx_ = { 0, 0, 1, -1 }; static int[] dy_ = { 1, -1, 0, 0 }; static int[] dx = { 1, 0, -1, 1, -1, 1, 0, -1 }, dy = { 1, 1, 1, 0, 0, -1, -1, -1 }; static Scanner scan = new Scanner(System.in); static int INF = 2147483647; // finds GCD of a and b using Euclidian algorithm public int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } static List<String> toList(String[] a) { return Arrays.asList(a); } static String[] toArray(List<String> a) { String[] o = new String[a.size()]; a.toArray(o); return o; } static int[] pair(int... a) { return a; } static int si() { return scan.nextInt(); } static String ss() { return scan.nextLine(); } static int[] sai(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = si(); return a; } static int[] sai_(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = si(); return a; } static String[] sas(int n) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) a[i] = ss(); return a; } static Object[][] _sm1(int r, int c) { Object[][] a = new Object[r][c]; for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) a[i][j] = scan.next(); return a; } static Object[][] _sm2(int r) { Object[][] a = new Object[r][3]; for (int i = 0; i < r; i++) a[i] = new Object[] { ss(), ss(), ss() }; return a; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
aaac13cb1beb8cdebdf789e81114c9b4
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; import java.util.*; public class Main2 { static class Main { Main() {} public Scanner sc; public int solve(int[] to, int v) { int r = 0; while (v != -1) { r++; v = to[v]; } return r; } public void run() { int n = sc.nextInt(); int[] to = new int[n]; for (int i = 0; i < n; i++) { int p = sc.nextInt(); if (p == -1) to[i] = p; else to[i] = p - 1; } int ans = 0; for (int i = 0; i < n; i++) { ans = Math.max(ans, solve(to, i)); } System.out.println(ans); } } public static void main(String[] args) { Main main = new Main(); try { main.sc = new Scanner(new FileInputStream("test.in")); } catch (FileNotFoundException e) { main.sc = new Scanner(System.in); } main.run(); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
44bd097c66e6bd1e7fe23622b0d2e3b8
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class A { /** * @param args */ static int[] a; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n= sc.nextInt(); a = new int[n]; int[] b = new int[n]; int k=0; Node[] nodes = new Node[n]; for (int i=0; i<n; i++) nodes[i] = new Node(i); for (int i=0; i<n; i++){ int p = sc.nextInt()-1; if (p==-2) { b[k++] = i; } else nodes[p].add(i); } int counter = 0; for (int i=0; i<k; i++){ int p = dfs(nodes, b[i]); if (p>counter) counter=p; } System.out.println(counter); } public static int dfs(Node[] nodes, int i){ if (nodes[i].size()==0) return 1; int k = 0; for (int j=0; j<nodes[i].size(); j++){ int p = dfs(nodes,nodes[i].get(j)); if (p>k) k =p; } return k+1; } } class Node{ public int index; ArrayList<Integer> lst = new ArrayList<Integer>(); public int get(int i){ return lst.get(i); } public int size(){ return lst.size(); } public void add(int p){ lst.add(p); } public Node(int index){ this.index = index; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
82d4b23f531a6d8f55c072828cf4de7f
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int pCount = in.nextInt(); ArrayList<Node> nodes = new ArrayList<Node>(); for(int i = 0; i < pCount; ++i) { Node n = new Node(); nodes.add(n); } for(int i = 0; i < pCount; ++i) { int j = in.nextInt(); if(j == -1) { continue; }else { Node superior = nodes.get(j - 1); Node inferior = nodes.get(i); inferior.parents.add(superior); } } int answer = 0; for(Node n : nodes) { int c = compute(n); n.parentCount = c; answer = Math.max(answer,c); } System.out.println(answer + 1); } public static int compute(Node x) { int c = x.parents.size(); for(Node i : x.parents) { c += compute(i); } return c; } public static class Node { ArrayList<Node> parents = new ArrayList<Node>(); int parentCount = 0; boolean visited = false; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
064af5ecb2234a6f6bd65465bdb4ffeb
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.Scanner; public class p115a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); emp1[] all = new emp1[n]; for (int i = 0; i < all.length; i++) { int m = in.nextInt(); if(m !=-1) m--; all[i] = new emp1(i , m); } int max = 0; for (int i = 0; i < all.length; i++) { int count = 1; int now = i; while(all[now].manager != -1) { count++; now = all[now].manager; } max = Math.max(count, max); } System.out.println(max); } } class emp1 { int num; int manager; public emp1(int a , int b) { num = a; manager = b; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
6d1f68d431693e807eba574ae8516253
train_003.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Party115A { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Input n"); int n = sc.nextInt(); int[] a = new int[n+1]; for (int i=1; i<=n; i++) { // System.out.println("Input manager number"); a[i] = sc.nextInt(); } int mingroups = 1; for (int i=1; i<=n; i++) { int lenfromhere = 1; int j = a[i]; while (j != -1) { j = a[j]; lenfromhere++; } if (lenfromhere > mingroups) { mingroups = lenfromhere; } } System.out.println(mingroups); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 6
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output