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 | 636a70f76d8fcba8fdbc170cd2926ab2 | train_003.jsonl | 1536248100 | You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str, " ");
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
String string = br.readLine();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (!map.containsKey(string.charAt(i))) {
map.put(string.charAt(i), 1);
} else {
map.put(string.charAt(i), 1 + map.get(string.charAt(i)));
}
}
if (map.size() != k) {
pw.println(0);
} else {
int min = Integer.MAX_VALUE;
Collection<Integer> coll = map.values();
for (int temp : coll) {
min = Math.min(min, temp);
}
pw.println(min * k);
}
pw.close();
}
} | Java | ["9 3\nACAABCCAB", "9 4\nABCABCABC"] | 2 seconds | ["6", "0"] | NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$. | Java 8 | standard input | [
"implementation",
"strings"
] | d9d5db63b1e48214d02abe9977709384 | The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet. | 800 | Print the only integerΒ β the length of the longest good subsequence of string $$$s$$$. | standard output | |
PASSED | cfb1b8792070d930a0687ec5eb9d8d0c | train_003.jsonl | 1536248100 | You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class cdf508a
{
static void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
public static int lowerBound(int[] array, int length, int value)
{
int low = 0;
int high = length;
while (low < high)
{
final int mid = (low + high) / 2;
//checks if the value is less than middle element of the array
if (value <= array[mid])
{
high = mid;
}
else
{
low = mid + 1;
}
}
return low;
}
public static int upperBound(int[] array, int length, int value)
{
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value >= array[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long power(long n,long m)
{
if(m==0)
return 1;
long ans=1;
while(m>0)
{
ans=ans*n;
m--;
}
return ans;
}
static int BinarySearch(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=1;//Integer.parseInt(br.readLine());
for(int i=1;i<=t;i++)
{
String s=br.readLine();
String str[]=s.split(" ");
int n=Integer.parseInt(str[0]);
int tot=Integer.parseInt(str[1]);
int arr[]=new int[tot];
s=br.readLine();
for(int j=0;j<n;j++)
arr[(int)s.charAt(j)-65]++;
sort(arr,0,tot-1);
System.out.println(arr[0]*tot);
}
}
}
| Java | ["9 3\nACAABCCAB", "9 4\nABCABCABC"] | 2 seconds | ["6", "0"] | NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$. | Java 8 | standard input | [
"implementation",
"strings"
] | d9d5db63b1e48214d02abe9977709384 | The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet. | 800 | Print the only integerΒ β the length of the longest good subsequence of string $$$s$$$. | standard output | |
PASSED | d881650ce527f10e379d5e6fb77d4ebc | train_003.jsonl | 1536248100 | You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Param
{
public static void main( String[]args)
{
MyScanner param = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n=param.nextInt();
int k=param.nextInt();
char []arr=new char[n];
int x=0;
String a=param.next();
for(int i=0;i<arr.length;i++){
arr[i]=a.charAt(i);
}
int []check=new int[k];
for(int i=0;i<arr.length;i++){
check[(int)arr[i]-65]++;
}
int max=check[0];
for(int i=0;i<check.length;i++){
if(max>check[i]){
max=check[i];
}
}
if(check.length!=k){
System.out.println("0");
}
else{
System.out.println(max*k);}
out.close();
}
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["9 3\nACAABCCAB", "9 4\nABCABCABC"] | 2 seconds | ["6", "0"] | NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$. | Java 8 | standard input | [
"implementation",
"strings"
] | d9d5db63b1e48214d02abe9977709384 | The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet. | 800 | Print the only integerΒ β the length of the longest good subsequence of string $$$s$$$. | standard output | |
PASSED | b491582173ef4d8139dc0b43843c1e90 | train_003.jsonl | 1536248100 | You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* https://codeforces.com/contest/1038/problem/A
*/
public class Solution1038A {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(System.in);
Scanner terminalInput = new Scanner(System.in);
int n = terminalInput.nextInt();
int k = terminalInput.nextInt();
String s = terminalInput.next();
out.print(count(n, k, s));
out.flush();
out.close();
// test();
}
private static int count(int n, int k, String s) {
String[] alpha = new String[k];
for(int i = 0; i < k; i++){
alpha[i] = String.valueOf((char)(65 + i));
}
StringBuilder sb = new StringBuilder(s);
int count = 0;
int index ;
while(true) {
for (String anAlpha : alpha) {
index = sb.indexOf(anAlpha);
if (index != -1) {
sb.deleteCharAt(index);
} else {
return count;
}
}
count += alpha.length;
}
}
private static void test() {
test(count(9, 3, "ACAABCCAB"), 6);
test(count(9, 4, "ABCABCABC"), 0);
test(count(5, 5, "ABCDE"), 5);
test(count(1, 1, "A"), 1);
test(count(1, 2, "A"), 0);
test(count(2, 2, "AB"), 2);
test(count(3, 2, "ABB"), 2);
test(count(4, 2, "ABBA"), 4);
test(count(5, 26, "ABBAZ"), 0);
test(count(26, 26, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 26);
test(count(53, 26, "ABCGHIJKLMDNOPSTUVDEFGHQRSTUVWXYZMNOPQRIJKLABCDEFWXYZ"), 52);
}
private static void test(int actual, int expected) {
if (actual != expected) {
System.out.println(actual + " != " + expected);
}
}
/**
* Copied from @author Egor Kulikov
*/
static class InputReader {
private InputStream stream;
private BufferedReader reader;
private byte[] buf = new byte[1024];
private InputReader.SpaceCharFilter filter;
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
reader = new BufferedReader(new InputStreamReader(stream));
}
public String readString() {
return reader.lines().collect(Collectors.joining("\n"));
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
} | Java | ["9 3\nACAABCCAB", "9 4\nABCABCABC"] | 2 seconds | ["6", "0"] | NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$. | Java 8 | standard input | [
"implementation",
"strings"
] | d9d5db63b1e48214d02abe9977709384 | The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet. | 800 | Print the only integerΒ β the length of the longest good subsequence of string $$$s$$$. | standard output | |
PASSED | db5d4869c5a46db41617e9da8421161a | train_003.jsonl | 1525007700 | One department of some software company has $$$n$$$ servers of different specifications. Servers are indexed with consecutive integers from $$$1$$$ to $$$n$$$. Suppose that the specifications of the $$$j$$$-th server may be expressed with a single integer number $$$c_j$$$ of artificial resource units.In order for production to work, it is needed to deploy two services $$$S_1$$$ and $$$S_2$$$ to process incoming requests using the servers of the department. Processing of incoming requests of service $$$S_i$$$ takes $$$x_i$$$ resource units.The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $$$S_i$$$ is deployed using $$$k_i$$$ servers, then the load is divided equally between these servers and each server requires only $$$x_i / k_i$$$ (that may be a fractional number) resource units.Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services. | 256 megabytes | import java.io.*;
import java.util.*;
public class VK_B implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
String filename = "";
if (!filename.isEmpty()) {
in = new BufferedReader(new FileReader(filename + ".in"));
out = new PrintWriter(filename + ".out");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new VK_B().run();
// new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
class Server implements Comparable<Server> {
int index, cores;
Server(int i, int c) {
this.index = i;
this.cores = c;
}
@Override
public int compareTo(Server o) {
return cores - o.cores;
}
}
class Answer {
List<Integer> server1 = new ArrayList<>();
List<Integer> server2 = new ArrayList<>();
}
Answer solve(int skipCount, Server[] servers, int x1, int x2) {
int first = servers[skipCount].cores;
int remaining = servers.length - skipCount;
int needCount = (x1 + first - 1) / first;
if (needCount >= remaining) return null;
int second = servers[skipCount + needCount].cores;
int needCount2 = (x2 + second - 1) / second;
int rem = servers.length - needCount - skipCount;
if (needCount2 > rem) return null;
Answer answer = new Answer();
for (int i = 0; i < needCount; i++) {
answer.server1.add(servers[skipCount + i].index + 1);
}
for (int i = 0; i < needCount2; i++) {
answer.server2.add(servers[skipCount + needCount + i].index + 1);
}
return answer;
}
private void solve() throws IOException {
int n = readInt();
int x1 = readInt();
int x2 = readInt();
Server[] a = new Server[n];
for (int i = 0; i < n; i++) {
a[i] = new Server(i, readInt());
}
Arrays.sort(a);
for (int sk = 0; sk < a.length; sk++) {
Answer answer = solve(sk, a, x1, x2);
if (answer == null) {
answer = solve(sk, a, x2, x1);
if (answer != null) {
List<Integer> t = answer.server1;
answer.server1 = answer.server2;
answer.server2 = t;
}
}
if (answer == null) {
continue;
}
out.println("Yes");
out.println(answer.server1.size() + " " + answer.server2.size());
for (int x : answer.server1) out.print(x + " ");
out.println();
for (int x : answer.server2) out.print(x + " ");
out.println();
return;
}
out.println("No");
}
}
| Java | ["6 8 16\n3 5 2 9 8 7", "4 20 32\n21 11 11 12", "4 11 32\n5 5 16 16", "5 12 20\n7 8 4 11 9"] | 2 seconds | ["Yes\n3 2\n1 2 6\n5 4", "Yes\n1 3\n1\n2 3 4", "No", "No"] | NoteIn the first sample test each of the servers 1, 2 and 6 will will provide $$$8 / 3 = 2.(6)$$$ resource units and each of the servers 5, 4 will provide $$$16 / 2 = 8$$$ resource units.In the second sample test the first server will provide $$$20$$$ resource units and each of the remaining servers will provide $$$32 / 3 = 10.(6)$$$ resource units. | Java 8 | standard input | [
"sortings",
"binary search",
"implementation"
] | aa312ddd875b82eab84fdc92ceec37e5 | The first line contains three integers $$$n$$$, $$$x_1$$$, $$$x_2$$$ ($$$2 \leq n \leq 300\,000$$$, $$$1 \leq x_1, x_2 \leq 10^9$$$)Β β the number of servers that the department may use, and resource units requirements for each of the services. The second line contains $$$n$$$ space-separated integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^9$$$)Β β the number of resource units provided by each of the servers. | 1,700 | If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes). In the second line print two integers $$$k_1$$$ and $$$k_2$$$ ($$$1 \leq k_1, k_2 \leq n$$$)Β β the number of servers used for each of the services. In the third line print $$$k_1$$$ integers, the indices of the servers that will be used for the first service. In the fourth line print $$$k_2$$$ integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them. | standard output | |
PASSED | 0f7f935f90b2a05bf45106cbd8c69d55 | train_003.jsonl | 1511449500 | Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If aiβ>β0, then ai bourles are deposited to Luba's account. If aiβ<β0, then ai bourles are withdrawn. And if aiβ=β0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when aiβ=β0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ljy
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt(), d = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] sum = new int[n];
int[] suf = new int[n];
sum[0] = a[0];
for (int i = 1; i < n; i++) {
sum[i] = sum[i - 1] + a[i];
}
suf[n - 1] = sum[n - 1];
for (int i = n - 2; i >= 0; i--) {
suf[i] = Math.max(suf[i + 1], sum[i]);
}
if (suf[0] > d) {
out.println(-1);
return;
}
int now = 0, ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
if (now + sum[i] < 0) {
int fly = Math.max(0, d - suf[i] - now);
now += fly;
ans++;
if (now + sum[i] - a[i] < 0) {
out.println(-1);
return;
}
}
}
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"] | 2 seconds | ["0", "-1", "2"] | null | Java 11 | standard input | [
"dp",
"implementation",
"greedy",
"data structures"
] | c112321ea5e5603fd0c95c4f01808db1 | The first line contains two integers n, d (1ββ€βnββ€β105, 1ββ€βdββ€β109) βthe number of days and the money limitation. The second line contains n integer numbers a1,βa2,β... an (β-β104ββ€βaiββ€β104), where ai represents the transaction in i-th day. | 1,900 | Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money. | standard output | |
PASSED | f0e38d3c47de83a50f18fa5c552340ed | train_003.jsonl | 1511449500 | Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If aiβ>β0, then ai bourles are deposited to Luba's account. If aiβ<β0, then ai bourles are withdrawn. And if aiβ=β0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when aiβ=β0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her! | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter out = new PrintWriter(System.out);
static Reader in = new Reader();
public static void main(String[] args) throws IOException {
Main solver = new Main();
solver.solve();
out.flush();
out.close();
}
static int INF = (int)1e9;
static int maxn = (int)1e5+5;
static int mod = 998244353;
static int n,m,q,k,t;
static ArrayList<Integer> adj[];
static int[] c;
static boolean[] vis;
void solve() throws IOException{
n = in.nextInt();
int d = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = in.nextInt();
long[] pre = new long[n];
pre[0] = arr[0];
for (int i = 1; i < n; i++) pre[i] = pre[i-1]+arr[i];
long[] max = new long[n];
max[n-1] = 0;
TreeSet<Long> set = new TreeSet<Long>();
long tmp = 0;
for (int i = n-1; i > 0; i--) {
set.add(-pre[i]);
tmp = -set.first();
max[i] = tmp-pre[i-1];
}
set.add(-pre[0]);
max[0] = -set.first();
long cur = 0;
boolean flag = true;
int ans = 0;
for (int i = 0; i < n; i++) {
if (cur+max[i] > d) flag = false;
if (arr[i] == 0 && cur < 0) {
tmp = d-(cur+max[i]);
cur+= tmp;
ans++;
if (cur < 0) flag = false;
}
cur+=arr[i];
}
if (flag) out.println(ans);
else out.println(-1);
}
//<>
static int tmp;
static void dfs(int s) {
vis[s] = true;
tmp = Math.min(tmp, c[s]);
for (int e:adj[s]) {
if (!vis[e]) {
dfs(e);
}
}
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"] | 2 seconds | ["0", "-1", "2"] | null | Java 11 | standard input | [
"dp",
"implementation",
"greedy",
"data structures"
] | c112321ea5e5603fd0c95c4f01808db1 | The first line contains two integers n, d (1ββ€βnββ€β105, 1ββ€βdββ€β109) βthe number of days and the money limitation. The second line contains n integer numbers a1,βa2,β... an (β-β104ββ€βaiββ€β104), where ai represents the transaction in i-th day. | 1,900 | Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money. | standard output | |
PASSED | 2573e6ac5aadc5f00314d81e4f3a43e7 | train_003.jsonl | 1511449500 | Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If aiβ>β0, then ai bourles are deposited to Luba's account. If aiβ<β0, then ai bourles are withdrawn. And if aiβ=β0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when aiβ=β0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
static long MOD=(long) (1e9+7);
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer s=new StringTokenizer(br.readLine());
int n=Integer.parseInt(s.nextToken());
int d =Integer.parseInt(s.nextToken());
s=new StringTokenizer(br.readLine());
int arr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=Integer.parseInt(s.nextToken());
}
long amount=0;
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
if(amount<0)
amount=0;
}else {
amount+=arr[i];
if(amount>d) {
pw.println(-1);
pw.close();
}
}
}
amount=0;
int ans=0;
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
if(amount<0) {
ans++;
amount=d;
}
}else {
amount+=arr[i];
if(amount>d)
amount=d;
}
}
pw.println(ans);
pw.close();
}
} | Java | ["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"] | 2 seconds | ["0", "-1", "2"] | null | Java 11 | standard input | [
"dp",
"implementation",
"greedy",
"data structures"
] | c112321ea5e5603fd0c95c4f01808db1 | The first line contains two integers n, d (1ββ€βnββ€β105, 1ββ€βdββ€β109) βthe number of days and the money limitation. The second line contains n integer numbers a1,βa2,β... an (β-β104ββ€βaiββ€β104), where ai represents the transaction in i-th day. | 1,900 | Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money. | standard output | |
PASSED | 8d059e84335e7621b99000df4aa479ba | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
ArrayList<Edge>[] tree;
int N;
public void solve(int testNumber, InputReader in, PrintWriter out) {
N = in.nextInt();
tree = new ArrayList[N];
if (N == 2) {
out.println(0);
} else {
for (int i = 0; i < N; i++) {
tree[i] = new ArrayList<>();
}
for (int i = 0; i < N - 1; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
tree[a].add(new Edge(b, i));
tree[b].add(new Edge(a, i));
}
int cnt = 0;
int[] ans = new int[N - 1];
Arrays.fill(ans, -1);
for (int i = 0; i < N; i++) {
if (tree[i].size() == 1) {
ans[tree[i].get(0).i] = cnt++;
}
}
if (cnt <= 1) {
for (int j = 0; j < N - 1; j++) {
out.println(j);
}
} else {
for (int i = 0; i < N - 1; i++) {
if (ans[i] == -1) {
out.println(cnt++);
} else {
out.println(ans[i]);
}
}
}
}
}
class Edge {
int a;
int i;
Edge(int a, int i) {
this.a = a;
this.i = i;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | f69b8884a7157fc0761bd5a461683759 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner nik = new Scanner(System.in);
int n = nik.nextInt();
HashMap<Integer, HashSet<Integer>> ht = new HashMap<>();
int[][] a = new int[n][2];
for (int i = 0; i < n - 1; i++) {
a[i][0] = nik.nextInt();
a[i][1] = nik.nextInt();
put(ht, a[i][0], a[i][1]);
put(ht, a[i][1], a[i][0]);
}
HashMap<String, Integer> a1 = new HashMap<>();
int maxe = -1;
int max = 0;
for (int val : ht.keySet()) {
HashSet<Integer> hm = ht.get(val);
if (hm.size() > max) {
max = hm.size();
maxe = val;
}
}
HashSet<Integer> ht1 = ht.get(maxe);
int idx = 0;
for (int val : ht1) {
String temp = maxe + " " + val;
a1.put(temp, idx);
idx++;
}
StringBuilder st = new StringBuilder();
for (int i = 0; i < n - 1; i++) {
String temp = a[i][0] + " " + a[i][1];
String temp1 = a[i][1] + " " + a[i][0];
if (a1.containsKey(temp)) {
st.append(a1.get(temp) + "\n");
} else if (a1.containsKey(temp1)) {
st.append(a1.get(temp1) + "\n");
} else {
st.append(idx + "\n");
idx++;
}
}
System.out.println(st);
}
private static void put(HashMap<Integer, HashSet<Integer>> ht, int i, int j) {
HashSet<Integer> hm = new HashSet<>();
if (ht.containsKey(i)) {
hm = ht.get(i);
}
hm.add(j);
ht.put(i, hm);
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | bda6e647428912fdd17610a3fceceec8 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class R628C {
public static void main(String[] args) throws Exception {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int N=Integer.parseInt(in.readLine());
List<List<Integer>> //neighbors=new ArrayList<>(),
edgeidxs=new ArrayList<>();
for (int i=0; i<N; i++) {
//neighbors.add(new ArrayList<>());
edgeidxs.add(new ArrayList<>());
}
int[] deg=new int[N];
for (int i=0; i<N-1; i++) {
StringTokenizer tok=new StringTokenizer(in.readLine());
int u=Integer.parseInt(tok.nextToken())-1,
v=Integer.parseInt(tok.nextToken())-1;
//neighbors.get(u).add(v);
edgeidxs.get(u).add(i);
//neighbors.get(v).add(u);
edgeidxs.get(v).add(i);
deg[u]++;
deg[v]++;
}
int rt=0;
while (rt<N && deg[rt]<3)
rt++;
int[] labels=new int[N-1];
Arrays.fill(labels,-1);
if (rt==N) {
//path tree
for (int i=0; i<N-1; i++)
labels[i]=i;
}
else {
for (int ni = 0; ni < 3; ni++)
labels[edgeidxs.get(rt).get(ni)] = ni;
for (int e = 0, l = 3; e < N - 1; e++) {
if (labels[e] == -1) {
labels[e] = l;
l++;
}
}
}
StringBuilder s=new StringBuilder();
for (int l:labels)
s.append(l).append("\n");
System.out.println(s);
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 2482d26e1c772fc83a14abd19699e265 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | /*
[ ( ^ _ ^ ) ]
*/
import java.io.*;
import java.util.*;
public class test {
int INF = (int)1e9;
long MOD = 1000000007;
void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int[][] e = new int[n-1][2];
int[] deg = new int[n];
for(int i=0; i<n-1; i++) {
e[i][0] = in.nextInt()-1;
e[i][1] = in.nextInt()-1;
deg[e[i][0]]++;
deg[e[i][1]]++;
}
int c = 0;
for(int i=0; i<n; i++) {
if(deg[i]==1) c++;
}
if(c>=3) {
int[] o = new int[n-1];
int x = 1;
loop1: for(int i=0; i<n-1; i++) {
for(int j=0; j<=1; j++) {
if(deg[e[i][j]]==1) {
o[i] = x++;
deg[e[i][j]]++;
}
if(x>3) {
break loop1;
}
}
}
x--;
for(int i=0; i<n-1; i++) {
if(o[i]>0) {
out.println(o[i]-1);
} else {
out.println(x++);
}
}
} else {
for(int i=0; i<n-1; i++) {
out.println(i);
}
}
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
while(t-- >0) {
new test().solve(in, out);
}
out.close();
}
public static void show(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | aa38f0f446914caa7e946779e6560435 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int[] v = new int[n+1];
int node = 0;
boolean done = false;
int[][] edge = new int[n][2];
for(int i = 0; i < n-1; i++) {
StringTokenizer st = new StringTokenizer(in.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
v[a]++;
v[b]++;
edge[i] = new int[] {a, b};
if(v[a] >= 3 && !done) {
node = a;
done = true;
}
if(v[b] >= 3 && !done) {
node = b;
done = true;
}
}
int count = 0;
int count2 = 3;
for(int i = 0; i < n-1; i++) {
if(done) {
if((edge[i][0] == node || edge[i][1] == node) && count < 3) {
System.out.println(count);
count++;
} else {
System.out.println(count2);
count2++;
}
} else {
System.out.println(count);
count++;
}
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 788a5e47746e9b58765b9f7b4a8a4fc4 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution
{
public static void main(String args[])throws IOException
{
FastReader in=new FastReader(System.in);
int i,j;
int fg=0;
//long min=Long.MAX_VALUE;
//long max=Long.MIN_VALUE;
//int t=in.nextInt();
int t=1;
for(i=0;i<t;i++)
{
int n=in.nextInt();
Integer EdgecountOfNodes[]=new Integer[n+1];
Integer answer[]=new Integer[n];
for(i=0;i<n-1;i++)
{
answer[i]=n+1;
EdgecountOfNodes[i]=0;
}
EdgecountOfNodes[n-1]=0;
EdgecountOfNodes[n]=0;
ArrayList<Integer> el=new ArrayList<>();
ArrayList<Integer> er=new ArrayList<>();
for(i=0;i<n-1;i++)
{
int n1=in.nextInt();
int n2=in.nextInt();
EdgecountOfNodes[n1]++;
EdgecountOfNodes[n2]++;
el.add(n1);
er.add(n2);
}
for(i=1;i<n-1;i++)
{
if(EdgecountOfNodes[el.get(i)]==1 || EdgecountOfNodes[er.get(i)]==1)
{
answer[i]=fg;
fg++;
}
}
for(j=0;j<n-1;j++)
{
if(answer[j]==n+1)
{
answer[j]=fg;
fg++;
}
}
for(j=0;j<n-1;j++)
{
System.out.println(answer[j]);
}
}
return;
}
}
class A
{
int a;
int b;
public A(int a,int b)
{
this.a=a;
this.b=b;
}
}
class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | bc15d493ff89d2860689efce738635ef | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class C628_PC {
public static ArrayList<pair>[] adj;
public static int n;
public static int[] ans;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
n = Integer.parseInt(st.nextToken());
adj = new ArrayList[n];
ans = new int[n-1];
for(int i =0;i<n;i++)
adj[i] = new ArrayList<pair>();
for(int i =0;i<n-1;i++)
{
st = new StringTokenizer(in.readLine());
int u = Integer.parseInt(st.nextToken())-1;
int v = Integer.parseInt(st.nextToken())-1;
adj[u].add(new pair(v,i));
adj[v].add(new pair(u,i));
ans[i] = -1;
}
int ind = 0;
int max = 0;
for(int i = 0;i<n;i++)
{
if(adj[i].size()>max)
{
max = adj[i].size();
ind = i;
}
}
int c = 0;
for(pair i:adj[ind])
ans[i.y] = c++;
for(int i = 0;i<n-1;i++)
{
if(ans[i]==-1)
ans[i] = c++;
System.out.println(ans[i]);
}
}
static class pair implements Comparable<pair>
{
int x,y;
public pair(int x, int y)
{
this.x = x;
this.y = y;
}
public int compareTo(pair that)
{
return (this.y-this.x)-(that.y-that.x);
}
public String toString()
{
return x+"-"+y;
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 92c313ec3ed6588be992e67803b80fa4 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
Reader in = new Reader();
int num = in.nextInt();
ArrayList<Integer>[] graph = new ArrayList[num + 1];
Integer[] ans = new Integer[num];
for(int x = 0; x <= num; x++) {
graph[x] = new ArrayList();
}
for(int x = 1; x < num; x++) {
int ver1 = in.nextInt();
int ver2 = in.nextInt();
graph[ver1].add(x);
graph[ver2].add(x);
}
int val = 0;
for(int x = 1; x <= num; x++) {
if(graph[x].size() > 2) {
ans[graph[x].get(0)] = 0;
ans[graph[x].get(1)] = 1;
ans[graph[x].get(2)] = 2;
val = 3;
break;
}
}
if(val == 0) {
for (int x = 1; x < num; x++) {
System.out.println(x - 1);
}
}
else {
for(int x = 1, ele = 3; x < num; x++) {
if(ans[x] == null) {
System.out.println(ele++);
}
else {
System.out.println(ans[x]);
}
}
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 86819d3eb98f17587fc4d6009a0f9e3f | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
public class TaskC {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
int[][] a = new int[n-1][4];
Map<Integer,ArrayList<int[]>> map = new HashMap<Integer, ArrayList<int[]>>();
for(int i=0;i<=n;i++) {
map.put(i, new ArrayList<int[]>());
}
for (int i = 0; i < n-1; i++) {
a[i][0] = i;
a[i][1] = in.nextInt();
a[i][2] = in.nextInt();
a[i][3] = -1;
map.get(a[i][1]).add(a[i]);
map.get(a[i][2]).add(a[i]);
}
int [][] g = new int[n+1][2];
for(int i=1;i<=n;i++) {
g[i][0]=i;
g[i][1]=map.get(i).size();
}
Arrays.sort(g, (el1, el2) -> el1[1]-el2[1]);
int cnt = 0;
for(int i=0; i<=n; i++) {
int node = g[i][0];
Iterator<int[]> edges =map.get(node).iterator();
while(edges.hasNext()) {
int[] edge = edges.next();
if(edge[3]<0) {
edge[3]=cnt;
cnt++;
}
}
}
for(int i=0;i<a.length;i++) {
out.printf("%d%n", a[i][3]);
}
out.close();
in.close();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | ef165519e1c180824303faf09ebfe700 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.StringTokenizer;
public class C {
static int crossroad = -1;
static int crossroadSize = -1;
static class Graph {
int V;
LinkedList<Integer> adjListArray[];
Graph(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<>();
}
}
}
static void addEdge(Graph graph, int src, int dest) {
graph.adjListArray[src].add(dest);
graph.adjListArray[dest].add(src);
if (graph.adjListArray[src].size() >= 3) {
crossroad = src;
crossroadSize = graph.adjListArray[src].size();
}
if (graph.adjListArray[dest].size() >= 3) {
crossroad = dest;
crossroadSize = graph.adjListArray[dest].size();
}
}
static LinkedList<Integer> neigh(Graph g, int i) {
return g.adjListArray[i];
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int nodes = in.nextInt();
Graph g = new Graph(nodes);
int u, v;
int[][] inputs = new int[nodes - 1][2];
for (int i = 0; i < nodes - 1; i++) {
u = in.nextInt();
v = in.nextInt();
inputs[i][0] = u - 1;
inputs[i][1] = v - 1;
addEdge(g, inputs[i][0], inputs[i][1]);
}
int counter = 0;
if (crossroad == -1)
counter = 0;
else
counter = crossroadSize;
for (int i = 0; i < nodes - 1; i++) {
if (inputs[i][0] == crossroad || inputs[i][1] == crossroad) {
out.println(--crossroadSize);
out.flush();
} else {
out.println(counter);
counter++;
out.flush();
}
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 64000);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | bcedb0bf3fc0dd04f1a4e799e311cc61 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class TaskC {
private static ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
private static HashMap<Edge, Integer> edges = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
ArrayList<Edge> edgesInOrder = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
edges.put(new Edge(a, b), -1);
edgesInOrder.add(new Edge(a, b));
adj.get(a).add(b);
adj.get(b).add(a);
}
int maxNbrs = 0;
int root = -1;
for (int i = 0; i < adj.size(); i++) {
ArrayList<Integer> list = adj.get(i);
if (list.size() > maxNbrs) {
maxNbrs = list.size();
root = i;
}
}
int count = 0;
LinkedList<Pair> q = new LinkedList<>(); // pair = node, parent
q.push(new Pair(root, -1));
while (!q.isEmpty()) {
Pair head = q.poll();
for (Integer nbr : adj.get(head.a)) {
if (nbr == head.b) continue;
Edge e = edges.containsKey(new Edge(nbr, head.a)) ? new Edge(nbr, head.a) : new Edge(head.a, nbr);
edges.put(e, count++);
q.add(new Pair(nbr, head.a));
}
}
for (Edge e : edgesInOrder) {
pw.println(edges.get(e));
}
pw.close();
}
static class Pair {
int a, b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static class Edge {
int a, b;
public Edge(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Edge edge = (Edge) o;
return a == edge.a &&
b == edge.b;
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public String toString() {
return "Edge{" +
"a=" + (a+1) +
", b=" + (b+1) +
'}';
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 68d25c92e5d5d3a9c9079f3e2f0d1ef9 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable{
FastScanner sc;
PrintWriter pw;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args)
{
new Thread(null,new Main(),"codeforces",1<<25).start();
}
public void run()
{
sc=new FastScanner();
pw=new PrintWriter(System.out);
int t=1;
while(t-->0)
solve();
pw.flush();
pw.close();
}
public long gcd(long a,long b)
{
return b==0L?a:gcd(b,a%b);
}
//////////////////////////////////
///////////// LOGIC ///////////
////////////////////////////////
public void solve()
{
int n=sc.ni();
int[] deg=new int[n];
int[] arr=new int[n];
int[] brr=new int[n];
for(int i=0;i<n-1;i++)
{
int x=sc.ni()-1;
int y=sc.ni()-1;
deg[x]++;
deg[y]++;
arr[i]=x;
brr[i]=y;
}
int[] col=new int[n-1];
if(n==2)
{
pw.println("0");
return;
}
Arrays.fill(col,-1);
int tmp=0;
for(int i=0;i<n-1;i++)
{
if(deg[arr[i]]==1||deg[brr[i]]==1)
col[i]=tmp++;
}
for(int i=0;i<n-1;i++)
{if(col[i]==-1)
col[i]=tmp++;
pw.println(col[i]);
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 49a959e5160fd750d96e276cd836598a | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), tree[][] = new int[n - 1][2], occur[] = new int[n], ans[] = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
int x = in.nextInt() - 1, y = in.nextInt() - 1;
tree[i][0] = x;
tree[i][1] = y;
occur[x]++;
occur[y]++;
}
int result = 0;
HashSet<Integer> ashset = new HashSet<>();
for (int i = 0; i < n; i++) {
}
for (int i = 0; i < n - 1; i++) {
int x = tree[i][0], y = tree[i][1];
if (occur[x] == 1 || occur[y] == 1) {
ans[i] = result;
result++;
ashset.add(i);
}
}
for (int i = 0; i < 1222; i++) {
}
for (int i = 0; i < n - 1; i++)
if (!ashset.contains(i)) {
ans[i] = result;
result++;
}
StringBuilder str = new StringBuilder();
for (int v : ans)
str.append(v + "\n");
System.out.println(str);
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 6952b78f61f998ba9613005f6d8f7720 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | 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.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class ehab_mex {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
cf_em.init(System.in);
int n=cf_em.nextInt();
emg g=new emg(n);
// HashMap<int[],Integer> hm=new HashMap<int[],Integer>();
int[][] ans=new int[n-1][3];
int[] degree=new int[n];
for(int x=0;x<n-1;x++) {
int u=cf_em.nextInt();
int v=cf_em.nextInt();
u--;
v--;
degree[u]++;
degree[v]++;
// int[] tmp=new int[2];
// tmp[0]=u;
// tmp[1]=v;
// hm.put(tmp,-2);
ans[x][0]=u;
ans[x][1]=v;
ans[x][2]=-2;
g.add_edge(u, v);
}
int ind=-2;
for(int r=0;r<n;r++) {
if(degree[r]>=3) {
ind=r;
}
}
if(ind==-2) {
for(int p=0;p<n-1;p++) {
System.out.println(p);
}
}
else {
int ctr=0;
for(int r=0;r<n-1;r++) {
if(ind==ans[r][0] || ind==ans[r][1]) {
ans[r][2]=ctr;
ctr++;
}
}
for(int q=0;q<n-1;q++) {
if(ans[q][2]==-2) {
ans[q][2]=ctr;
ctr++;
}
}
for(int e=0;e<n-1;e++) {
System.out.println(ans[e][2]);
}
}
//// HashMap<int[],Integer> arr=new HashMap<int[],Integer>();
// HashMap<Integer,HashMap<Integer,Integer>> arr=new HashMap<Integer,HashMap<Integer,Integer>>();
//
// HashMap<Integer,Integer> extra=new HashMap<Integer,Integer>();
//
// arr=g.bfs();
//
// for(int p=0;p<n-1;p++) {
// int[] ch=new int[2];
// ch[0]=Math.min(ans[p][0], ans[p][1]);
// ch[1]=Math.max(ans[p][0], ans[p][1]);
//// System.out.print(ch[0]+" "+ch[1]+" ");
// extra=arr.get(ch[0]);
// int num=extra.get(ch[1]);
// System.out.println(num);
// }
}
}
class cf_ed{
int u;
int v;
int val;
cf_ed(int a,int b,int c){
u=a;
v=b;
val=c;
}
}
class emg{
int n;
ArrayList<ArrayList<Integer>> adj;
emg(int V){
n=V;
adj=new ArrayList<ArrayList<Integer>>();
for(int h=0;h<n;h++){
adj.add(new ArrayList<Integer>());
}
}
void add_edge(int a,int b){
adj.get(a).add(b);
adj.get(b).add(a);
}
HashMap<Integer,HashMap<Integer,Integer>> bfs() {
int[] assign=new int[n-1];
for(int w=0;w<n-1;w++) {
if(w==n-2 && n-2>=2) {
assign[w]=2;
}
else if(w>=2) {
assign[w]=w+1;
}
else {
assign[w]=w;
}
}
int[] dist=new int[n];
dist[0]=1;
Queue<Integer> q=new LinkedList<Integer>();
q.add(0);
int ind=0;
HashMap<Integer,Integer> extra=new HashMap<Integer,Integer>();
HashMap<Integer,HashMap<Integer,Integer>> hm=new HashMap<Integer,HashMap<Integer,Integer>>();
int[][] ans=new int[n-1][3];
while(!q.isEmpty()) {
int u=q.poll();
for(int e=0;e<adj.get(u).size();e++) {
int v=adj.get(u).get(e);
if(dist[v]==0) {
dist[v]=1;
int[] tmp=new int[2];
tmp[0]=Math.min(u, v);
tmp[1]=Math.max(u, v);
// System.out.println(tmp[0]+" "+tmp[1]+" "+assign[ind]);
extra.put(tmp[1],assign[ind]);
hm.put(tmp[0], extra);
ind++;
q.add(v);
}
}
}
return hm;
}
}
/** Class for buffered reading int and double values */
class cf_em {
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());
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 9d35c6e924323c31b2f399acd1ba3a0a | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
public static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char)c;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
static long func(long a[],long size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static void main(String args[]){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int n=in.nextInt(),i,j,k;
LinkedList<Integer> li[]=new LinkedList[n+1];
for(i=0;i<=n;i++){
li[i]=new LinkedList<>();
}
int v[]=new int[n];
int u[]=new int[n];
for(i=0;i<n-1;i++){
v[i]=in.nextInt();
u[i]=in.nextInt();
li[v[i]].add(u[i]);
li[u[i]].add(v[i]);
}
int m=0,ma=0;
for(i=0;i<=n;i++){
if(li[i].size()>=3){
m=i;
break;
}
}
if(m==0){
m=1;
}
int ans[]=new int[n-1];
int c=0;
for(i=0;i<n-1;i++){
ans[i]=-1;
}
for(i=0;i<n-1;i++){
if(v[i]==m||u[i]==m){
ans[i]=c;
c++;
}
}
for(i=0;i<n-1;i++){
if(ans[i]==-1){
ans[i]=c;
c++;
}
}
for(i=0;i<n-1;i++){
w.println(ans[i]);
}
w.close();
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 853bdc657a8721a7702809edbbb1c6fe | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=sc.nextInt();
int arr[]=new int[n+1];
int l[]=new int[n];
int r[]=new int[n];
int lf=0;
int nf=n-2;
for(int i=0;i<n-1;i++){
int a=sc.nextInt();
l[i]=a;
arr[a]++;
int b=sc.nextInt();
r[i]=b;
arr[b]++;
}
for(int i=0;i<n-1;i++){
if(arr[l[i]]==1 || arr[r[i]]==1){
w.println(lf);
lf++;
}
else {
w.println(nf);
nf--;
}
}
w.close();
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 5e13ec50dcfca6ac6639a4cc4b43d444 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
import java.util.Stack;
public class minjumps{
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static FastReader sc = new FastReader();
static int mod = (int) (1e9+7);
static List<Pair>[] edges ;
public static void main(String[] args) {
int n = sc.nextInt();
edges = new ArrayList[n+1];
for(int i=0;i<=n;++i) edges[i] = new ArrayList<>();
Pair[] p = new Pair[n];
for(int i=1;i<n;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
p[i] = new Pair(u,v);
edges[u].add(new Pair(v,i));
edges[v].add(new Pair(u,i));
}
int cnt = 0;
int[] ans = new int[n];
Arrays.fill(ans, -1);
for(int i=1;i<=n;++i) {
if(edges[i].size() == 1) {
if(ans[edges[i].get(0).idx] == -1) {
ans[edges[i].get(0).idx]=cnt;
++cnt;
}
}
}
for(int i=1;i<n;++i) {
if(ans[i] != -1)
out.println(ans[i]);
else {
out.println(cnt);
++cnt;
}
}
// boolean[] a = new boolean[n+1];
//
// Queue<Pair> q = new LinkedList<>();
// q.add(p[1]);
// a[p[1].v] = true;
// int cnt = -1;
// p[1].idx = cnt++;
// while(q.size() > 0) {
// Pair node = q.poll();
// for(Pair pr : edges[node.v]) {
// if(!a[pr.v]) {
// q.add(pr);
// a[pr.v] = true;
// p[pr.idx].idx = cnt++;
// }
// }
// }
// for(int i=1;i<n;++i) out.println(p[i].idx);
//
out.close();
}
static class Pair implements Comparable<Pair>{
int v;
int idx;
Pair(int v,int idx){
this.v = v;
this.idx = idx;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.v-o.v;
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | d2b90d7363e79c25e5dbcdfd8282fd66 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Pick questions that you love and solve them with love, try to get AC in one
* go with cleanest code Just one thing to keep in mind these questions should
* be out of your reach, which make you step out of comfort zone Try to pick
* them from different topics CP is a sport, enjoy it. Don't make it pressure
* cooker or job ****Use pen and paper************* check few examples analyze
* them, some not given in sample also analyze then code Use pen and paper.
* Solve on paper then code. If there is some reasoning e.g. sequence/paths, try
* printing first 100 elements or 100 answers using brute and observe.
* *********Read question with extreme caution. Mistake is happening here which
* costs time, WA and easy problem not getting solved.********* Sometimes we
* make question complex due to misunderstanding. Prefix sum and suffix sum is
* highly usable concept, look for it. Think of cleanest approach. If too many
* if else are coming then its indication of WA. Solve 1-2 more questions than
* you solved during contest.
*/
public class Codeforces {
private static final String NEWLINE = "\n";
private static final String SPACE = " ";
public static void main(String args[]) throws IOException {
// FastReader in = new FastReader(); use in case of millions of strings
Reader in = new Reader();
// int t = in.nextInt();
// while (t-->0) {
int n = in.nextInt();
LinkedList<Integer> g[] = new LinkedList[n];
for (int i=0;i<n;i++) g[i] = new LinkedList<Integer>();
for (int i=1;i<n;i++) {
int u = in.nextInt()-1, v = in.nextInt()-1;
g[u].add(i);
g[v].add(i);
}
int ans[] = new int[n];
Arrays.fill(ans, -1);
int cnt = 0;
for (int i=0;i<n;i++) {
if (g[i].size()<=2) continue;
for (int v:g[i]) {
if (ans[v] == -1) ans[v] = cnt++;
}
}
for (int i=1;i<n;i++) {
if (ans[i] == -1) ans[i] = cnt++;
System.out.println(ans[i]);
}
// }
in.close();
}
static class Pair {
Integer x;
Integer y;
private Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Pair))
return false;
Pair cor = (Pair) o;
return x.equals(cor.x) && y.equals(cor.y);
}
@Override
public int hashCode() {
int result = 17;
return result;
}
static class PairComparatorX implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
return o1.x.compareTo(o2.x);
}
}
static class PairComparatorY implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
return o1.y.compareTo(o2.y);
}
}
}
static class Reader {
/**
* When reading millions of strings try using FastReader if getting tle
*/
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
Scanner in = new Scanner(System.in);
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
String next() {
return in.next();
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
if (in == null)
return;
in.close();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 9589c4439a2a5d144b99d7067f49b21d | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn=new Scanner(System.in);
int n =scn.nextInt();
int [][] arr =new int[n-1][2];
for(int i=0;i<n-1;i++){
arr[i][0]=scn.nextInt();
arr[i][1]=scn.nextInt();
}
res(arr,n);
}
public static void res(int [][]arr ,int n){
ArrayList<ArrayList<pair>> al =new ArrayList<>();
for(int i=0;i<n;i++){
al.add(new ArrayList<>());
}
int [] arr2 = new int[arr.length];
Arrays.fill(arr2, -1);
for(int i=0;i<arr.length;i++){
// System.out.println(arr[i][0]);
ArrayList<pair> al1 =al.get(arr[i][0]-1);
al1.add(new pair(arr[i][1]-1,i));
ArrayList<pair> al2 = al.get(arr[i][1]-1);
al2.add(new pair(arr[i][0]-1,i));
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<arr.length;i++){
if(al.get(i).size()<=2){
continue;
}
ArrayList<pair> al2 = al.get(i);
int j=0;
for(pair val : al2){
if(j==3){
break;
}
arr2[val.idx]=j;
j++;
}
for(i=0;i<arr.length;i++){
if(arr2[i]==-1){
//System.out.println(j);
sb.append(j+"\n");
j++;
}else{
sb.append(arr2[i]+"\n");
}
}
System.out.print(sb);
return;
}
for(int i=1;i<n;i++){
sb.append((i-1)+"\n");
}
System.out.print(sb);
}
public static class pair{
int val ;
int idx;
public pair(int val ,int idx){
this.val=val;
this.idx=idx;
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 69cf905a465bd15f175b9ee08a8ac45d | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class DIV2C_Ehab_and_Path_etic_MEXs {
private static final StreamTokenizer IN = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
private static final PrintWriter OUT = new PrintWriter(new OutputStreamWriter(System.out));
private int n;
private Map<Integer, List<Edge>> edges = new HashMap<>();
private int[] ans;
private class Edge {
int index;
int lable = -1;
public Edge(int index) {
this.index = index;
}
}
private void input() {
n = nextInt();
ans = new int[n-1];
Arrays.fill(ans, -1);
for (int i = 0; i < n - 1; i++) {
int u = nextInt();
int v = nextInt();
List<Edge> children = edges.getOrDefault(u, new ArrayList<>(8));
children.add(new Edge(i));
if (children.size() == 1) {
edges.put(u, children);
}
children = edges.getOrDefault(v, new ArrayList<>(8));
children.add(new Edge(i));
if (children.size() == 1) {
edges.put(v, children);
}
}
}
private void process() {
AtomicInteger lable = new AtomicInteger(0);
int root = -1;
int maxChildren = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
if (root == -1 || maxChildren < edges.get(i).size()) {
root = i;
maxChildren = edges.get(i).size();
}
}
if (root != -1) {
List<Edge> children = edges.get(root);
for (int i = 0; i < children.size(); i++) {
children.get(i).lable = i;
}
}
edges.values().stream().flatMap(List::stream)
.filter(e -> e.lable >= 0)
.peek(e -> ans[e.index] = e.lable)
.count();
int mark = n - 2;
for (int i = 0; i < n - 1; i++) {
if (ans[i] == -1) {
ans[i] = mark--;
}
}
}
private void output() {
Arrays.stream(ans).forEach(System.out::println);
OUT.flush();
}
private static int nextInt() {
try {
if (IN.nextToken() != StreamTokenizer.TT_EOF) {
return (int) IN.nval;
} else {
throw new EOFException();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String nextStr() {
try {
if (IN.nextToken() != StreamTokenizer.TT_EOF) {
return IN.sval;
} else {
throw new EOFException();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
DIV2C_Ehab_and_Path_etic_MEXs main = new DIV2C_Ehab_and_Path_etic_MEXs();
main.input();
main.process();
main.output();
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 5a957670ebc0738783d2d86a1bf112ca | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | // package codeForces;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;
public class TEhabPatheticMEXs {
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t =1;
while (t > 0) {
int n=i();
ArrayList<ArrayList<Integer>> ar=new ArrayList<>(n+1);
for(int i=0;i<=n;i++) {
ar.add(new ArrayList<>());
}
for(int i=1;i<n;i++) {
int a=i();
int b=i();
ar.get(a).add(i);
ar.get(b).add(i);
}
pair pa[]=new pair[n+1];
pa[0]=new pair(0,0);
for(int i=1;i<=n;i++) {
pa[i]=new pair(ar.get(i).size(),i);
// System.out.println(pa[i].x+" "+pa[i].y);
}
// System.out.println(pa[1].x);
Arrays.sort(pa, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return p1.x - p2.x;
}
});
// System.out.println(pa[1].x+" check ");
int ans[]=new int[n+1];
Arrays.fill(ans, -1);
int count=0;
for(int j:ar.get(pa[n].y)) {
ans[j]=count++;
}
for(int i=1;i<n;i++) {
if(ans[i]==-1)
ans[i]=count++;
System.out.println(ans[i]);
}
t--;
}
// long l=l();
// String s=s(); // ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER
}
public static long pow(long a, long b) {
long m = 1000000007;
long result = 1;
while (b > 0) {
if (b % 2 != 0) {
result = (result * a) % m;
b--;
}
a = (a * a) % m;
b /= 2;
}
return result % m;
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static void pln(String value) {
System.out.println(value);
}
public static int i() {
return in.Int();
}
public static String s() {
return in.String();
}
}
class pair {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class CompareValue {
static void compare(pair arr[], int n) {
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return p1.y - p2.y;
}
});
}
}
class CompareKey {
static void compare(pair arr[], int n) {
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return p2.x - p1.x;
}
});
}
}
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 Int() {
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 String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, Int());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, Int());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
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]);
}
writer.flush();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
}
/**
* TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
* DESC ORDER OF SECOND
* LIST name-list
* ARRAYLIST
* COPY PASTE
*
* Collections.sort(list, (first,second) ->{
if(first.con >second.con)
return -1;
else if(first.con<second.con)
return 1;
else {
if(first.index >second.index)
return 1;
else
return -1;
}
});
*
*/
/**
*
DECIMAL FORMATTER
Double k = in.readDouble();
System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */ | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 5c70a2b0eb9c7cf85191e87dfecd3ca7 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | //package learning;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NitsLocal {
static ArrayList<String> s1;
static boolean[] prime;
static int n = (int)1e7;
static void sieve() {
Arrays.fill(prime , true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k<= n ; k+=i) {
prime[k] = false;
}
}
}
}
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
n *= 2;
prime = new boolean[n + 1];
//sieve();
prime[1] = false;
/*
int n = sc.ni();
int k = sc.ni();
int []vis = new int[n+1];
int []a = new int[k];
for(int i=0;i<k;i++)
{
a[i] = i+1;
}
int j = k+1;
int []b = new int[n+1];
for(int i=1;i<=n;i++)
{
b[i] = -1;
}
int y = n - k +1;
int tr = 0;
int y1 = k+1;
while(y-- > 0)
{
System.out.print("? ");
for(int i=0;i<k;i++)
{
System.out.print(a[i] + " ");
}
System.out.flush();
int pos = sc.ni();
int a1 = sc.ni();
b[pos] = a1;
for(int i=0;i<k;i++)
{
if(a[i] == pos)
{
a[i] = y1;
y1++;
}
}
}
ArrayList<Integer> a2 = new ArrayList<>();
if(y >= k)
{
int c = 0;
int k1 = 0;
for(int i=1;i<=n;i++)
{
if(b[i] != -1)
{
c++;
a[k1] = i;
a2.add(b[i]);
k1++;
}
if(c==k)
break;
}
Collections.sort(a2);
System.out.print("? ");
for(int i=0;i<k;i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
System.out.flush();
int pos = sc.ni();
int a1 = sc.ni();
int ans = -1;
for(int i=0;i<a2.size();i++)
{
if(a2.get(i) == a1)
{
ans = i+1;
break;
}
}
System.out.println("!" + " " + ans);
System.out.flush();
}
else
{
int k1 = 0;
a = new int[k];
for(int i=1;i<=n;i++)
{
if(b[i] != -1)
{
a[k1] = i;
a2.add(b[i]);
k1++;
}
}
for(int i=1;i<=n;i++)
{
if(b[i] == -1)
{
a[k1] = i;
k1++;
if(k1==k)
break;
}
}
int ans = -1;
while(true)
{
System.out.print("? ");
for(int i=0;i<k;i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
System.out.flush();
int pos = sc.ni();
int a1 = sc.ni();
int f = 0;
if(b[pos] != -1)
{
Collections.sort(a2);
for(int i=0;i<a2.size();i++)
{
if(a2.get(i) == a1)
{
ans = i+1;
f = 1;
System.out.println("!" + " " + ans);
System.out.flush();
break;
}
}
if(f==1)
break;
}
else
{
b[pos] = a1;
a = new int[k];
a2.add(a1);
for(int i=1;i<=n;i++)
{
if(b[i] != -1)
{
a[k1] = i;
a2.add(b[i]);
k1++;
}
}
for(int i=1;i<=n;i++)
{
if(b[i] == -1)
{
a[k1] = i;
k1++;
if(k1==k)
break;
}
}
}
}
*/
int n = sc.ni();
int [][]node = new int[n-1][2];
int []d = new int[n+1];
int []ans = new int[n-1];
int u = 0;
for(int i=0;i<n-1;i++)
{
node[i][0] = sc.ni();
node[i][1] = sc.ni();
ans[i] = -1;
d[node[i][0]]++;
d[node[i][1]]++;
}
for(int i=0;i<n-1;i++)
{
if(d[node[i][0]] == 1 || d[node[i][1]] == 1)
{
ans[i] = u;
u++;
}
}
for(int i=0;i<n-1;i++)
{
if(ans[i] == -1)
{
ans[i] = u;
u++;
}
}
for(int i=0;i<n-1;i++)
{
w.println(ans[i] + " ");
}
w.close();
}
static class Student{
int time;
int l;
long h;
Student(int time,int l,long h)
{
this.time = time;
this.l = l;
this.h = h;
}
}
static int upperBound(ArrayList<Integer> a, int low, int high, int element){
while(low < high){
int middle = low + (high - low)/2;
if(a.get(middle) >= element)
high = middle;
else
low = middle + 1;
}
return low;
}
static long func(long t,long e,long h,long a, long b)
{
if(e*a >= t)
return t/a;
else
{
return e + Math.min(h,(t-e*a)/b);
}
}
public static int upperBound(int []arr,int n,int num)
{
int l = 0;
int r = n;
while(l < r)
{
int mid = (l+r)/2;
if(num >= arr[mid])
{
l = mid +1;
}
else
r = mid;
}
return l;
}
public static int countSetBits(int number){
int count = 0;
while(number>0){
++count;
number &= number-1;
}
return count;
}
static HashSet<Integer> fac;
public static void primeFactors(int n)
{
// Print the number of 2s that divide n
int t = 0;
while (n%2==0)
{
fac.add(2);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i*i <= n; i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
fac.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
fac.add(n);
}
static long modexp(long x,long n,long M)
{
long power = n;
long result=1;
x = x%M;
while(power>0)
{
if(power % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
power = power/2;
}
return result;
}
static long modInverse(long A,long M)
{
return modexp(A,M-2,M);
}
static long gcd(long a,long b)
{
if(a==0)
return b;
else
return gcd(b%a,a);
}
static class Temp{
int a;
int b;
int c;
int d;
Temp(int a,int b,int c,int d)
{
this.a = a;
this.b = b;
this.c =c;
this.d = d;
//this.d = d;
}
}
static long sum1(int t1,int t2,int x,int []t)
{
int mid = (t2-t1+1)/2;
if(t1==t2)
return 0;
else
return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t);
}
static String replace(String s,int a,int n)
{
char []c = s.toCharArray();
for(int i=1;i<n;i+=2)
{
int num = (int) (c[i] - 48);
num += a;
num%=10;
c[i] = (char) (num+48);
}
return new String(c);
}
static String move(String s,int h,int n)
{
h%=n;
char []c = s.toCharArray();
char []temp = new char[n];
for(int i=0;i<n;i++)
{
temp[(i+h)%n] = c[i];
}
return new String(temp);
}
public static int ip(String s){
return Integer.parseInt(s);
}
static class multipliers implements Comparator<Long>{
public int compare(Long a,Long b) {
if(a<b)
return 1;
else if(b<a)
return -1;
else
return 0;
}
}
static class multipliers1 implements Comparator<Student>{
public int compare(Student a,Student b) {
if(a.time<b.time)
return -1;
else if(b.time<a.time)
return 1;
else
{
if(a.h < b.h)
return 1;
else if(b.h<a.h)
return -1;
else
{
return 0;
}
//return 0;
}
}
}
// Java program to generate power set in
// lexicographic order.
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static PrintWriter w = new PrintWriter(System.out);
static class Student1
{
int id;
//int x;
int b;
//long z;
Student1(int id,int b)
{
this.id = id;
//this.x = x;
//this.s = s;
this.b = b;
// this.z = z;
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | faad4c03a254427fee3ef32130be7599 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class TaskC {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
Graph g = new Graph(n);
for(int i=0 ; i<n-1 ; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken())-1;
int y = Integer.parseInt(st.nextToken())-1;
g.addEdge(x, y, i);
}
g.solve();
pw.flush();
pw.close();
}
}
class Graph {
int n;
HashMap<Integer, Integer>[] adj;
int[] val;
Graph(int v) {
n = v;
adj = new HashMap[n];
val = new int[n-1];
Arrays.fill(val, -1);
for(int i=0 ; i<n ; i++) adj[i] = new HashMap<>();
}
void addEdge(int a, int b, int c) {
adj[a].put(b, c);
adj[b].put(a, c);
}
void solve() {
PrintWriter pw = new PrintWriter(System.out);
if(n == 2) {
pw.println(0);
}
else {
int assign = 0;
for(int i=0 ; i<n ; i++) {
if(adj[i].size() == 1) {
for(Map.Entry<Integer, Integer> ent: adj[i].entrySet()) {
val[ent.getValue()] = assign;
assign++;
}
}
}
for(int i=0 ; i<n-1 ; i++) {
if(val[i] == -1) {
val[i] = assign++;
}
}
for(int i=0 ; i<n-1 ; i++) pw.println(val[i]);
}
pw.flush();
pw.close();
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 3aa6ddcd5f48001f4bdd77954b99f6be | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
FastReader sc = new FastReader(); //For Fast IO
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
ArrayList<Integer> adj[] = new ArrayList[n+1];
int ans[] = new int[n+1];
Arrays.fill(ans,-1);
for(int i=1;i<=n;i++){
adj[i]=new ArrayList<>();
}
for(int i=1;i<n;i++){
int x = sc.nextInt();
int y = sc.nextInt();
adj[x].add(i);
adj[y].add(i);
}
Pair max = new Pair(0,0);
for(int i=1;i<=n;i++){
int size = adj[i].size();
int node = i;
if(max.x<size && max.y<node){
max = new Pair(size,node);
}
}
int curr=0;
for(Integer edgeno : adj[max.y]){
ans[edgeno] = curr++;
}
for(int i=1;i<n;i++){
if(ans[i]==-1){
ans[i]=curr++;
}
sb.append(ans[i]+"\n");
}
System.out.println(sb);
}
}
class Pair{
int x;
int y;
Pair(int i,int j){
x=i;
y=j;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31*result + y;
return result;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | d0fe9a35673f39f60289a43aea24089d | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
FastReader sc = new FastReader(); //For Fast IO
int n = sc.nextInt();
ArrayList<Integer> adj[] = new ArrayList[n+1];
int ans[] = new int[n+1];
Arrays.fill(ans,-1);
for(int i=1;i<=n;i++){
adj[i]=new ArrayList<>();
}
for(int i=1;i<n;i++){
int x = sc.nextInt();
int y = sc.nextInt();
adj[x].add(i);
adj[y].add(i);
}
Pair max = new Pair(0,0);
for(int i=1;i<=n;i++){
int size = adj[i].size();
int node = i;
if(max.x<size && max.y<node){
max = new Pair(size,node);
}
}
int curr=0;
for(Integer edgeno : adj[max.y]){
ans[edgeno] = curr++;
}
for(int i=1;i<n;i++){
if(ans[i]==-1){
ans[i]=curr++;
}
System.out.println(ans[i]);
}
}
}
class Pair{
int x;
int y;
Pair(int i,int j){
x=i;
y=j;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31*result + y;
return result;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 877c1eef3c8bfa8d85c8afa8222592ec | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeSet;
public final class CF_628_D2_C
{
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputFlush(Object o){try {out.write(""+ o+"\n");out.flush();} catch (Exception e) {}}
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static void test() {
log("testing");
Random r=new Random();
int NTESTS=100000;
int NMAX=10;
for (int t=0;t<NTESTS;t++) {
}
log("done");
}
static int pgcd(int a,int b) {
if (a<b)
return pgcd(b,a);
while (b>0) {
int c=b;
b=a%b;
a=c;
}
return a;
}
static long pgcd(long a,long b) {
if (a<b)
return pgcd(b,a);
while (b>0) {
long c=b;
b=a%b;
a=c;
}
return a;
}
static int[] anc;
static int[] h;
static int[] stack;
static int[] how;
static int dfs(ArrayList<Integer>[] friends,ArrayList<Integer>[] edges,int node) {
int n=friends.length;
anc=new int[n];
how=new int[n];
stack=new int[n];
h=new int[n];
int st=0;
stack[st++]=node;
anc[node]=-1;
how[node]=-1;
int max=-1;
int target=-1;
while (st>0) {
int u=stack[st-1];
st--;
for (int i=0;i<friends[u].size();i++) {
int v=friends[u].get(i);
int e=edges[u].get(i);
if (v!=anc[u]) {
anc[v]=u;
how[v]=e;
h[v]=h[u]+1;
stack[st++]=v;
if (h[v]>max) {
max=h[v];
target=v;
}
}
}
}
return target;
}
static void process() throws Exception {
//log("hello");
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader = new InputReader(System.in);
int n=reader.readInt();
ArrayList<Integer>[] friends=new ArrayList[n];
ArrayList<Integer>[] edges=new ArrayList[n];
for (int i=0;i<n;i++) {
friends[i]=new ArrayList<Integer>();
edges[i]=new ArrayList<Integer>();
}
for (int i=0;i<n-1;i++) {
int u=reader.readInt()-1;
int v=reader.readInt()-1;
friends[u].add(v);
friends[v].add(u);
edges[u].add(i);
edges[v].add(i);
}
int[] res=new int[n-1];
Arrays.fill(res,-1);
int end1=dfs(friends,edges,0);
int end2=dfs(friends,edges,end1);
int u=end2;
int e=how[u];
//log("first e:"+e);
res[e]=0;
int ref=n-2;
//log("end1:"+end1+" end2:"+end2);
while (anc[u]!=end1) {
u=anc[u];
e=how[u];
if (anc[u]==end1) {
//log("case 1");
res[e]=1;
} else {
//log("case 2");
res[e]=ref--;
}
//log("u:"+u+" e:"+e+" "+res[e]+" "+anc[u]+" "+end1);
}
//log(res);
for (e=0;e<n-1;e++) {
if (res[e]==-1)
res[e]=ref--;
output(res[e]);
}
try {
out.close();
} catch (Exception Ex) {
}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final String readString(int L) throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder(L);
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
/*
5
1 4 5 2 3
*/ | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 17e4fdd92c3cfbee4b1571af7b220cdd | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
public class code2 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader scn = new FastReader();
int n = scn.nextInt();
int b[] = new int[n-1];
int c[] = new int[n];
Pair arr[] = new Pair[n-1];
for(int i=0; i<n-1; i++) {
int u = scn.nextInt()-1;
int v = scn.nextInt()-1;
arr[i] = new Pair(u,v);
c[u]++;
c[v]++;
}
for(int i=0; i<n-1; i++)
b[i] = -1;
int k = 0;
for(int i=0; i<n-1; i++) {
int a1 = arr[i].first;
int a2 = arr[i].second;
if(c[a1]==1 || c[a2]==1) {
b[i] = k;
k++;
}
}
for(int i=0; i<n-1; i++) {
if(b[i]==-1) {
b[i] = k;
k++;
}
}
for(int i=0; i<n-1; i++)
System.out.println(b[i]);
}
public static class Pair{
int first;
int second;
Pair(int x, int y) {
first = x;
second = y;
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 9e5030a3fccc04b5501d0952f9e23230 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class tryyy {
static public class pair {
int u;
int idx;
int val;
public pair(int x, int i) {
u = x;
idx = i;
val = -1;
}
}
static public class trp implements Comparable<trp> {
int idx;
int val;
public trp(int v, int i) {
idx = i;
val=v;
}
@Override
public int compareTo(trp trp) {
return idx - trp.idx;
}
}
static int[] color;
static ArrayList<pair>[] adj;
static int[] min, max, ans1, ans2;
static int inf = (int) 1e9;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
adj[a].add(new pair(b, i));
adj[b].add(new pair(a, i));
}
int c = 0;
TreeSet<trp>ts=new TreeSet<>();
for (int i = 0; i < n; i++) {
if (adj[i].size() == 1){
trp t=new trp(c, adj[i].get(0).idx);
if (!ts.contains(t)) {
ts.add(t);
c++;
}
}
}
for (int i = 0; i < n; i++) {
for (pair p : adj[i])
{
trp t=new trp(c, p.idx);
if (!ts.contains(t)) {
ts.add(t);c++;
}
}
}
for(trp t:ts)pw.println(t.val);
pw.close();
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException, IOException {
return br.ready();
}
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 70462b79d108f8d856ba443a891234dd | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.TreeMap;
public class C {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputReader s = new InputReader(System.in);
PrintWriter p = new PrintWriter(System.out);
int n = s.nextInt();
Edges[] edge = new Edges[n];
int[] ans = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
ans[i] = -1;
}
Node[] graph = new Node[n];
for (int i = 0; i < n; i++) {
graph[i] = new Node(i);
}
for (int i = 0; i < n - 1; i++) {
int a = s.nextInt() - 1;
int b = s.nextInt() - 1;
edge[i] = new Edges(a, b);
graph[a].nbr.put(b, 1);
graph[b].nbr.put(a, 1);
}
ArrayList<Integer> leaf = new ArrayList<>();
int[] flag = new int[n];
for (int i = 0; i < n; i++) {
if (graph[i].nbr.size() == 1) {
flag[i] = 1;
}
}
int val = 0;
for (int i = 0; i < n - 1; i++) {
if (flag[edge[i].a]==1 || flag[edge[i].b]==1) {
ans[i] = val;
val++;
}
}
for (int i = 0; i < n - 1; i++) {
if (ans[i] == -1) {
ans[i] = val;
val++;
}
}
for (int i = 0; i < n - 1; i++) {
p.println(ans[i]);
}
p.flush();
p.close();
}
public static class Node {
int index;
HashMap<Integer, Integer> nbr;
Node(int index) {
this.index = index;
nbr = new HashMap<>();
}
}
public static class Edges {
int a, b;
Edges(int a, int b) {
this.a = a;
this.b = b;
}
}
public static ArrayList Divisors(long n) {
ArrayList<Long> div = new ArrayList<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
div.add(i);
if (n / i != i)
div.add(n / i);
}
}
return div;
}
public static int BinarySearch(long[] a, long k) {
int n = a.length;
int i = 0, j = n - 1;
int mid = 0;
if (k < a[0])
return 0;
else if (k >= a[n - 1])
return n;
else {
while (j - i > 1) {
mid = (i + j) / 2;
if (k >= a[mid])
i = mid;
else
j = mid;
}
}
return i + 1;
}
public static long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
public static long LCM(long a, long b) {
return (a * b) / GCD(a, b);
}
static class pair implements Comparable<pair> {
Integer x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
return result;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x - x == 0 && p.y - y == 0;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class CodeX {
public static void sort(long arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(long A[], long start, long end) {
if (start < end) {
long mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(long A[], long start, long mid, long end) {
long p = start, q = mid + 1;
long Arr[] = new long[(int) (end - start + 1)];
long k = 0;
for (int i = (int) start; i <= end; i++) {
if (p > mid)
Arr[(int) k++] = A[(int) q++];
else if (q > end)
Arr[(int) k++] = A[(int) p++];
else if (A[(int) p] < A[(int) q])
Arr[(int) k++] = A[(int) p++];
else
Arr[(int) k++] = A[(int) q++];
}
for (int i = 0; i < k; i++) {
A[(int) start++] = Arr[i];
}
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | d158ae2ff23cc68e038796d89bd447e1 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class EhabAndPatheticMEXs {
public static void main(String[] args) throws IOException{
Scan S = new Scan();
Print P = new Print();
int N, u, v;
N = S.scanInt();
List<List<Integer>> graph = new ArrayList<>(Collections.nCopies(N+1, null));
List<Integer> labels = new ArrayList<>(Collections.nCopies(N-1, 0));
for(int i=0; i<N-1; i++){
u = S.scanInt();
v = S.scanInt();
if(Objects.isNull(graph.get(u))){
graph.set(u, new ArrayList<>());
}
if(Objects.isNull(graph.get(v))){
graph.set(v, new ArrayList<>());
}
graph.get(u).add(i);
graph.get(v).add(i);
labels.set(i, -1);
}
int max_size = 0, max_node = 0;
for(int i=1; i<=N; i++){
if(graph.get(i).size()>max_size){
max_size = graph.get(i).size();
max_node = i;
}
}
int counter = 0;
for(Integer i : graph.get(max_node)){
labels.set(i.intValue(), counter);
counter++;
}
for(int i=0; i<N-1; i++){
if(labels.get(i)==-1){
labels.set(i, counter);
counter++;
}
}
for(Integer i: labels)
P.println(i);
P.close();
}
}
class Print {
private final BufferedWriter bw;
public Print() {
this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object)throws IOException {
bw.append(""+object);
}
public void println(Object object)throws IOException {
print(object);
bw.append("\n");
}
public void close()throws IOException {
bw.close();
}
}
class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan() {
in=System.in;
}
public int scan()throws IOException {
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException {
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public long scanLong()throws IOException {
long integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
long neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException {
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-') {
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.') {
if(n>='0'&&n<='9') {
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.') {
n=scan();
double temp=1;
while(!isWhiteSpace(n)) {
if(n>='0'&&n<='9') {
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException {
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n)) {
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 23192755596cd36df66f0f42e0d679fa | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import sun.reflect.generics.tree.Tree;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []a=new int[n+1];
int []b=new int[n+1];
int c[][]=new int[n-1][2];
for(int i=0;i<n-1;i++){
int x=sc.nextInt();
int y=sc.nextInt();
HashMap<Integer, Integer> map = new HashMap<>();
map.put(x,y);
c[i][0]=x;c[i][1]=y;
b[x]++;b[y]++;
}
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n+1;i++)
if(b[i]==1)
map.put(i,1);
int index=0;
int indexShort=n-2;
int j=0;
for(int i=0;i<n-1;i++){
Integer key = c[i][0];
Integer val = c[i][1];
if(map.get(key)!=null||map.get(val)!=null)
System.out.println(index++);
else
System.out.println(indexShort--);
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | aa457d5f2b779e79a4456ae13e5dc2ba | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static void main (String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
String[] temp=br.readLine().trim().split(" ");
int n=Integer.parseInt(temp[0]);
int[][] edges=new int[n-1][2];
int[] degree=new int[n+1];
for(int i=0;i<n-1;i++){
temp=br.readLine().trim().split(" ");
int u=Integer.parseInt(temp[0]);
int v=Integer.parseInt(temp[1]);
degree[u]++;
degree[v]++;
edges[i][0]=u;
edges[i][1]=v;
}
int count=0;
int[] ans=new int[n-1];
for(int i=0;i<n-1;i++){
int u=edges[i][0];
int v=edges[i][1];
if(degree[u]==1 || degree[v]==1)
{
ans[i]=count;
count++;
}
}
for(int i=0;i<n-1;i++){
int u=edges[i][0];
int v=edges[i][1];
if(degree[u]>1 && degree[v]>1){
ans[i]=count;
count++;
}
}
for(int i=0;i<n-1;i++){
out.println(ans[i]);
}
out.flush();
out.close();
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 60a898d64f0779b95f710d603529a6e7 | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> adjmat = new ArrayList<ArrayList<Integer>>();
TreeMap<Integer, TreeMap<Integer, Integer>>edj = new TreeMap();
for(int i=0;i<n;i++) {
adjmat.add(new ArrayList<Integer>());
edj.put(i, new TreeMap<Integer, Integer>());
}
Pair[] edges = new Pair[n-1];
for(int i=0;i<n-1;i++) {
int a = sc.nextInt();
int b = sc.nextInt();
edges[i] = new Pair(a-1, b-1);
adjmat.get(a-1).add(b-1);
adjmat.get(b-1).add(a-1);
}
if(n==2) {
pw.println(0);
}else {
int c = 0;
for(int i=0;i<adjmat.size();i++) {
if(adjmat.get(i).size()==1) {
edj.get(i).put(adjmat.get(i).get(0),c);
edj.get(adjmat.get(i).get(0)).put(i, c);
c++;
}
}
for(int i=0;i<edges.length;i++) {
if(edj.get(edges[i].a).get(edges[i].b)!=null)
pw.println(edj.get(edges[i].a).get(edges[i].b));
else pw.println(c++);
}
}
pw.flush();
pw.close();
}
}
class Pair {
int a,b;
public Pair(int a,int b) {
this.a = a;
this.b = b;
}
}
| Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 60827ba5b1f9301dde6d07432f9cae0e | train_003.jsonl | 1584196500 | You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class r628c {
public static void main(String[] args) {
//solution idea: prevent 0, 1, and 2 to be on the same path if at all possible
//if there is any node with degree>=3 we can put em all incident to that one
//else the tree is guaranteed to be a straight line and whatever we do we can't fix this
//so put them anywhere
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int n=scan.nextInt();
ArrayList<Integer>[] a=new ArrayList[n];
for(int i=0;i<n;i++) a[i]=new ArrayList<>();
int id=-1;
for(int i=0;i<n-1;i++) {
int u=scan.nextInt()-1, v=scan.nextInt()-1;
a[u].add(i);
a[v].add(i);
if(a[u].size()>=3) id=u;
if(a[v].size()>=3) id=v;
}
int[] res=new int[n-1];
Arrays.fill(res,-1);
boolean found=(id!=-1);
if(found) {
for(int j=0;j<=2;j++) res[a[id].get(j)]=j;
}
int start=found?3:0;
for(int i=0;i<n-1;i++) {
if(res[i]==-1) res[i]=start++;
out.println(res[i]);
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"] | 1 second | ["0\n1", "0\n3\n2\n4\n1"] | NoteThe tree from the second sample: | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"dfs and similar",
"trees"
] | 5ef966b7d9fbf27e6197b074eca31b15 | The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree. | 1,500 | Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order). | standard output | |
PASSED | 2a5b2caf818dad30401b38372cf268f1 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
//Codeforces
public class MainCodeforces1 {
private static MyScanner in;
private static PrintStream out;
public static void main(String[] args) throws IOException {
// helpers for input/output
boolean LOCAL_TEST = false;// change to false before submitting
out = System.out;
if (LOCAL_TEST) {
in = new MyScanner("E:\\zin2.txt");
}
else {
boolean usingFileForIO = false;
if (usingFileForIO) {
// using input.txt and output.txt as I/O
in = new MyScanner("input.txt");
out = new PrintStream("output.txt");
}
else {
in = new MyScanner();
out = System.out;
}
}
solve();
}
private static void solve() throws IOException
{
int N = in.nextInt();
int K = in.nextInt();
int ans;
int[] a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
long max = a[N - 1];
boolean[] used = new boolean[N];
for (int i = 0; i < N; i++) {
used[i] = true;
}
ans = 0;
for (int i = 0; i < N; i++) {
if (used[i]) {
ans++;
long mul = K * (long) a[i];
if (mul <= max) {
int index = Arrays.binarySearch(a, (int) mul);
if (index >= 0)
{
used[index] = false;
}
}
}
}
if (K == 1)
ans = N;
out.println(ans);
}
// =====================================
static class MyScanner {
Scanner inp = null;
public MyScanner() throws IOException
{
inp = new Scanner(System.in);
}
public MyScanner(String inputFile) throws IOException {
inp = new Scanner(new FileInputStream(inputFile));
}
public int nextInt() throws IOException {
return inp.nextInt();
}
public long nextLong() throws IOException {
return inp.nextLong();
}
public double nextDouble() throws IOException {
return inp.nextDouble();
}
public String nextString() throws IOException {
return inp.next();
}
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | bfb34e576884b44412e7b0a9e4c35ec8 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | /*
PROG: b
LANG: JAVA
*/
import java.util.*;
import java.io.*;
public class c {
int n, k;
private void solve() throws Exception {
//BufferedReader br = new BufferedReader(new FileReader("c.in"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer sc = new StringTokenizer(br.readLine());
n = Integer.parseInt(sc.nextToken());
k = Integer.parseInt(sc.nextToken());
Long[] a= new Long[n];
Set<Long> se = new HashSet<Long>();
boolean[] ha = new boolean[n];
sc = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i)
a[i] = Long.parseLong(sc.nextToken());
Arrays.sort(a);
for(int i = 0; i < n; ++i)
ha[i] = Arrays.binarySearch(a, a[i] * k) > -1;
for(int i = 0; i < n; ++i)
if(!se.contains(a[i]))
se.add(a[i] * k);
System.out.println(se.size());
}
public static void main(String[] args) throws Exception {
new c().solve();
}
static void debug(Object...o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | bdf945a0212e71e2be70d17438e1cfb3 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | /*
PROG: b
LANG: JAVA
*/
import java.util.*;
import java.io.*;
public class c {
int n, k;
private void solve() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer sc = new StringTokenizer(br.readLine());
n = Integer.parseInt(sc.nextToken());
k = Integer.parseInt(sc.nextToken());
Long[] a= new Long[n];
sc = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i)
a[i] = Long.parseLong(sc.nextToken());
Arrays.sort(a);
Set<Long> se = new HashSet<Long>();
for(int i = 0; i < n; ++i)
if(!se.contains(a[i]))
se.add(a[i] * k);
System.out.println(se.size());
}
public static void main(String[] args) throws Exception {
new c().solve();
}
static void debug(Object...o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 6f04f9138565d088a9e0a8179083f191 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;
public class C {
/**
* @param args
*/
public static void main(String[] args) {
KDivisibility kd = new KDivisibility();
kd.solve();
kd.print();
}
}
class KDivisibility {
KDivisibility() {
Scanner scr = new Scanner(System.in);
n = scr.nextInt();
k = scr.nextInt();
lst = new ArrayList<>();
for (int i = 0; i < n; i++){
lst.add(scr.nextInt());
}
Collections.shuffle(lst);
Collections.sort(lst);
answer = 0;
}
void solve() {
tree = new TreeSet<>();
tree.add(lst.remove(0));
for (int z: lst){
if ((z % k) != 0) {
tree.add(z);
}
else if (!tree.contains((z/k))){
tree.add(z);
}
}
answer = tree.size();
}
void print(){
System.out.println(answer);
}
int answer;
TreeSet<Integer> tree;
ArrayList<Integer> lst;
int n;
int k;
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 2b41bb70da53972460cccac3610d6dba | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
public class B {
static int N;
static PrintWriter out;
public static void main(String[] args) {
MScanner sc = new MScanner();
out = new PrintWriter(System.out);
int N = sc.nextInt();
long K = sc.nextInt();
HashSet<Long> HS = new HashSet<Long>();
long[] array =sc.nextLong(N);
Arrays.sort(array);
int done = 0;
for(int a=0;a<N;a++){
if(HS.contains(array[a]))continue;
done++;
HS.add(array[a]*K);
}
out.println(done);
out.close();
}
static class MScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public MScanner() {
stream = System.in;
// stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextInt(int N) {
int[] ret = new int[N];
for (int a = 0; a < N; a++)
ret[a] = nextInt();
return ret;
}
int[][] nextInt(int N, int M) {
int[][] ret = new int[N][M];
for (int a = 0; a < N; a++)
ret[a] = nextInt(M);
return ret;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLong(int N) {
long[] ret = new long[N];
for (int a = 0; a < N; a++)
ret[a] = nextLong();
return ret;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDouble(int N) {
double[] ret = new double[N];
for (int a = 0; a < N; a++)
ret[a] = nextDouble();
return ret;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] next(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = next();
return ret;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
String[] nextLine(int N) {
String[] ret = new String[N];
for (int a = 0; a < N; a++)
ret[a] = nextLine();
return ret;
}
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | d50462ab511ba12d98c52ccbf741a79d | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Collections;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
public class Round168ProblemC {
public static void main(String[] args) {
Reader r = new Reader();
int n = r.nextInt();
int k = r.nextInt();
int result = 0;
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(n,
Collections.reverseOrder());
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
queue.add(r.nextInt());
}
while (!queue.isEmpty()) {
int next = queue.poll();
if (!set.contains(next)) {
result++;
if (next % k == 0) {
set.add(next / k);
}
}
}
System.out.println(result);
}
static class Reader {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
public int nextInt() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (int) in.nval;
}
public String nextString() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return in.sval;
}
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 2fcb5f6de51a07d49297e4f07503208d | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solve {
public static void main(String[] args) throws FileNotFoundException {
//Scanner in = new Scanner(new FileReader("input.txt"));
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long k = in.nextLong();
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
Arrays.sort(a);
int ans = 0;
HashSet<Long> s = new HashSet<Long>();
for(int i = 0; i < n; i++) {
if (!s.contains(a[i])) {
ans++;
s.add(a[i] * k);
}
}
System.out.println(ans);
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 8199d0e748295e1611df77eda6213057 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class Maain implements Runnable{
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()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
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 Thread(null, new Maain(), "", 256 * (1L << 20)).start();
}
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());
}
}
}
int sm(int x){
if (x==1) return 0;else return 1;
}
void solve() throws IOException{
int n=readInt();
int k=readInt();
HashSet<Long> set=new HashSet<Long>();
long[] a=new long[n];
for (int i=0;i<n;i++){
a[i]=readLong();}
Arrays.sort(a);
for (int i=0;i<n;i++){
if (!set.contains(a[i])) {
set.add(k*a[i]);
}
}
System.out.println(set.size());
}
public void run(){
try{
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
//time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 8dda9d5a38ec5f3fcbf1926866dd67c5 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class C {
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 int N,K;
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc=new Scanner();
N=sc.nextInt();
K=sc.nextInt();
int[] m=new int[N];
for(int i = 0 ;i < N;i++)
m[i]=sc.nextInt();
Arrays.sort(m);
TreeSet<Integer> ans=new TreeSet<Integer>();
for(int i=0; i< N ;i++){
if (m[i] % K != 0){
ans.add(m[i]);
continue;
}
int t = m[i] / K ;
if (!ans.contains(t))
ans.add(m[i]);
}
//System.out.println(ans);
System.out.println(ans.size());
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 1040bb5cde59272e54ade8a78143eaa5 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*; //PrintWriter
import java.math.*; //BigInteger, BigDecimal
import java.util.*; //StringTokenizer, ArrayList
public class R168_Div2_C //Name: k-Mulitple Free Set
{
FastReader in;
PrintWriter out;
public static void main(String[] args) {
new R168_Div2_C().run();
}
void run()
{
in = new FastReader(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void solve()
{
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Arrays.sort(a);
//HashSet<Long> set = new HashSet<Long>();
TreeSet<Long> set = new TreeSet<Long>();
for (long i : a)
if (!set.contains(i))
set.add(i*k);
out.println(set.size());
}
//-----------------------------------------------------
void runWithFiles() {
in = new FastReader(new File("input.txt"));
try {
out = new PrintWriter(new File("output.txt"));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
solve();
out.close();
}
class FastReader
{
BufferedReader br;
StringTokenizer tokenizer;
public FastReader(InputStream stream)
{
br = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public FastReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
tokenizer = null;
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(br.readLine());
}
catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return br.readLine();
}
catch(Exception e) {
throw(new RuntimeException());
}
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 49b872bdc092e98cf6edff15461ba2dc | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*; //PrintWriter
import java.math.*; //BigInteger, BigDecimal
import java.util.*; //StringTokenizer, ArrayList
public class R168_Div2_C //Name: k-Mulitple Free Set
{
FastReader in;
PrintWriter out;
public static void main(String[] args) {
new R168_Div2_C().run();
}
void run()
{
in = new FastReader(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void solve()
{
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Arrays.sort(a);
HashSet<Long> set = new HashSet<Long>();
for (long i : a)
if (!set.contains(i))
set.add(i*k);
out.println(set.size());
}
//-----------------------------------------------------
void runWithFiles() {
in = new FastReader(new File("input.txt"));
try {
out = new PrintWriter(new File("output.txt"));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
solve();
out.close();
}
class FastReader
{
BufferedReader br;
StringTokenizer tokenizer;
public FastReader(InputStream stream)
{
br = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public FastReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
tokenizer = null;
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(br.readLine());
}
catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return br.readLine();
}
catch(Exception e) {
throw(new RuntimeException());
}
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | d39d43afe58c746b76384855e26d538b | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.sql.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Scanner;
import org.omg.CORBA.ARG_OUT;
public class CodeforcesRound168C
{
public static void main(String[] args) {
CodeforcesRound168C.run();
}
public static void run()
{
Scanner kde = new Scanner (System.in);
int n=kde.nextInt();
long k=kde.nextLong();
long[] m= new long[n];
int kol=0;
TreeSet<Long> set = new TreeSet<Long>();
for (int i=0; i<n; i++ )
{
m[i]=kde.nextLong();
}
Arrays.sort(m);
for (int i=0; i<n; i++ )
{
if(!set.contains((long)m[i]))
{
kol++;
set.add((long)m[i]*(long)k);
}
}
System.out.println(kol);
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | f8ae6479cc62739a6ecb1a3ff231379b | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(scan.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
//int n = Integer.parseInt(scan.readLine());
//String n = scan.readLine();
StringTokenizer st1 = new StringTokenizer(scan.readLine());
HashSet<Long> s1 = new HashSet<Long>();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(st1.nextToken());
}
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
if (!s1.contains(arr[i])) s1.add(arr[i] * k);
}
pw.println(s1.size());
pw.flush();
pw.close();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 0d1b5d2eeacf5b0790b3f27e7aaa7a56 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class C {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
TreeSet<Integer> hax = new TreeSet<>();
Integer[] list = new Integer[N];
for (int i = 0; i < N; i++) {
list[i] = sc.nextInt();
}
Arrays.sort(list);
for (int i = 0; i < N; i++) {
if (list[i] % K != 0) {
hax.add(list[i]);
} else {
if (!hax.contains(list[i] / K)) {
hax.add(list[i]);
}
}
}
out.println(hax.size());
sc.close();
out.close();
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 0da0b414d87960fd639d3259a2eb8db3 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class C {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
TreeSet<Integer> hax = new TreeSet<>();
int[] list = new int[N];
for (int i = 0; i < N; i++) {
list[i] = sc.nextInt();
}
Arrays.sort(list);
for (int i = 0; i < N; i++) {
if (list[i] % K != 0) {
hax.add(list[i]);
} else {
if (!hax.contains(list[i] / K)) {
hax.add(list[i]);
}
}
}
out.println(hax.size());
sc.close();
out.close();
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | b7ecfde86f0e8f69401b780173095151 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Task {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
/**
* ########################
* Solution
*/
int n = sc.nextInt();
int k = sc.nextInt();
long[] a = new long[n];
boolean[] d = new boolean[n];
for(int i = 0; i < n; i++)
{
a[i] = sc.nextInt();
}
Arrays.sort(a);
int count = 0;
for(int i = 0; i < n; i++)
{
if(d[i])
continue;
long b = a[i]*k;
int j = Arrays.binarySearch(a, b);
if(j >= 0)
{
d[j] = true;
}
count++;
}
out.println(count);
/**
* Solution
* ########################
*/
out.flush();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 1a6a124017f50a35a86a50022cc3d65d | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class C {
public static void main(String [] args){
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int [] b = new int[n];
TreeSet<Integer> al = new TreeSet();
for(int i = 0 ; i < n ; i++){
b[i]=in.nextInt();
}
Arrays.sort(b);
int ans = 0 ;
for(int i = 0 ; i < n ; i++){
if (b[i]%k==0){
if(!al.contains(b[i]/k)&&!al.contains(b[i])){
al.add(b[i]);
ans++;
}
}
else{
al.add(b[i]);
ans++;
}
}
System.out.println(ans);
}
}
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));
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
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 ;
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 768f1a1db5e2b8c5e4bfd6d3edd70035 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;
public class C2 {
public static void main (String args[]){
Scanner in = new Scanner(System.in);
TreeSet<Long> t = new TreeSet<Long>();
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for(int i = 0 ; i<n ; i++){
a[i] = in.nextInt();
}
Arrays.sort(a);
int res = 0 ;
for(int i = 0 ; i < n ; i++){
if(!t.contains((long)a[i])){
res++;
t.add((long)a[i]*(long)k);
}
}
System.out.println(res);
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 3f04dcd560586cdc9eeb1facc6ca017e | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class C {
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();long k = sc.nextLong();
long[] a = new long[n];
boolean[] used = new boolean[n];
for(int i=0;i<n;i++) a[i] = Long.parseLong(sc.next());
sort(a);
int cnt = 0;
for(int i=0;i<n;i++) if(!used[i]){
int p = binSearch(a, a[i]*k);
if( p > 0 ) {
used[p] = true;
}
cnt++;
}
System.out.println(cnt);
}
int binSearch(long[] a, long v) {
int l = 0, r = a.length;
while(l<r) {
int c = (l+r)/2;
debug(l+" "+ r+" " +a[c]+" "+ v);
if(a[c] == v) return c;
if( a[c] < v ) l = c+1;
if( a[c] > v ) r = c;
}
return -1;
}
void debug(Object... os) {
// System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new C().run();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | d01b0eabd9e0ffc936ed448da46735ef | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class C {
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();long k = sc.nextLong();
long[] a = new long[n];
boolean[] used = new boolean[n];
for(int i=0;i<n;i++) a[i] = Long.parseLong(sc.next());
sort(a);
int cnt = 0;
for(int i=0;i<n;i++) if(!used[i]){
int p = binSearch(a, a[i]*k);
if( p > 0 ) {
used[p] = true;
}
cnt++;
}
System.out.println(cnt);
}
int binSearch(long[] a, long v) {
int l = 0, r = a.length;
while(l<r) {
int c = (l+r)/2;
debug(l, r, a[c], v);
if(a[c] == v) return c;
if( a[c] < v ) l = c+1;
if( a[c] > v ) r = c;
}
return -1;
}
void debug(Object... os) {
// System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new C().run();
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | a20dcef1a58c373156a8a64056274f1d | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class C {
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();long k = sc.nextLong();
long[] a = new long[n];
boolean[] used = new boolean[n];
for(int i=0;i<n;i++) a[i] = Long.parseLong(sc.next());
sort(a);
int cnt = 0;
for(int i=0;i<n;i++) if(!used[i]){
int p = binSearch(a, a[i]*k);
if( p > 0 ) {
used[p] = true;
}
cnt++;
}
System.out.println(cnt);
}
int binSearch(long[] a, long v) {
int l = 0, r = a.length;
while(l<r) {
int c = (l+r)/2;
// debug(l, r, a[c], v);
if(a[c] == v) return c;
if( a[c] < v ) l = c+1;
if( a[c] > v ) r = c;
}
return -1;
}
void debug(Object... os) {
// System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new C().run();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | a449ed6c72d54f741d239870de75b1ae | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.util.Arrays;
import java.util.BitSet;
import java.util.Scanner;
public class Main {
Scanner sc = new Scanner(System.in);
void run() {
int n = sc.nextInt();
int k = sc.nextInt();
int list[] = new int[n];
for (int i = 0; i < n; i++) {
list[i] = sc.nextInt();
}
Arrays.sort(list);
if (k == 1) {
System.out.println(n);
return;
}
BitSet map = new BitSet(500000000);
int res = n;
for (int i = 0; i < n; i++) {
if (list[i] % k == 0) {
if (map.get(list[i] / k)) {
res--;
continue;
}
}
map.set(list[i]);
}
System.out.println(res);
}
public static void main(String[] a) {
Main m = new Main();
m.run();
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 2a83de01719910cbaa1d0bea6012dad1 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class C {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int n = myScanner.nextInt(), k = myScanner.nextInt();
myScanner.nextLine();
StringTokenizer tok = new StringTokenizer(myScanner.nextLine());
Long all[] = new Long[n];
TreeSet<Long> vis = new TreeSet<Long>();
int res = 0;
for (int i = 0; i < all.length; i++)
all[i] = new Long(tok.nextToken());
Arrays.sort(all);
for (int i = 0; i < all.length; i++) {
long tmp = all[i] * k;
if (!vis.contains(all[i])) {
res++;
vis.add(tmp);
}
}
System.out.println(res);
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 927cbc6be960c6c903968785a63080f4 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String [] args){
Scanner cin = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
int N = cin.nextInt(), k = cin.nextInt();
int []a = new int[N];
for (int i=0;i<N;++i)a[i] = cin.nextInt();
Arrays.sort(a);
if (k == 1){
cout.println(N);
cout.flush();
return;
}
boolean []used = new boolean[N];
for (int i=N-1;i>=0;--i)if (a[i] % k == 0 && !used[i]){
int ind = Arrays.binarySearch(a, a[i]/k);
if (ind >= 0)used[ind] = true;
}
int cnt = 0;
for (int i=0;i<N;++i)cnt += used[i]?0:1;
cout.println(cnt);
cout.flush();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 4bfd9c2766781e7fab321c8cbc5bab78 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
static final String FILE_NAME = "";
static final String INPUT_FILE = FILE_NAME + ".in";
static final String OUTPUT_FILE = FILE_NAME + ".out";
static final Locale locale = new Locale("US");
static final boolean DEBUG = System.getProperty("ONLINE_JUDGE") == null
&& System.getProperty("DEBUG") != null;
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
if (DEBUG) {
inputStream = new FileInputStream("in");
//outputStream = new FileOutputStream("output");
} else {
if (!INPUT_FILE.equals(".in") && !OUTPUT_FILE.equals(".out")) {
inputStream = new FileInputStream(INPUT_FILE);
outputStream = new FileOutputStream(OUTPUT_FILE);
}
}
Locale.setDefault(locale);
Input in = new Input(inputStream);
Output out = new Output(outputStream, DEBUG, locale);
Solver solver = new Solver(in, out);
try {
solver.solve();
} catch (Exception ex) {
if (DEBUG) {
out.println();
ex.printStackTrace(out);
} else {
throw ex;
}
}
in.close();
out.close();
}
}
class Solver {
public void solve() {
int n = in.nextInt(), k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) a[i] = in.nextInt();
sort(a);
Set<Integer> s = new TreeSet<Integer>();
int ans = 0;
for (int i = 0; i < n; ++i) {
if (a[i] % k != 0 || !s.contains(a[i] / k)) {
s.add(a[i]);
++ans;
}
}
out.println(ans);
}
private Input in;
private Output out;
public Solver(Input in, Output out) {
this.in = in;
this.out = out;
}
}
class Input {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Input(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return tokenizer.nextToken();
}
public byte nextByte() {
return Byte.parseByte(next());
}
public short nextShort() {
return Short.parseShort(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return next().charAt(0);
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public boolean hasNext() {
try {
return reader.ready();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void close() throws IOException {
reader.close();
}
}
class Output extends PrintWriter {
private final Locale defaultLocale;
public Output(OutputStream outputStream, boolean autoFlush, Locale defaultLocale) {
super(new BufferedWriter(new OutputStreamWriter(outputStream)), autoFlush);
this.defaultLocale = defaultLocale;
}
@Override
public PrintWriter printf(String format, Object... args) {
return super.printf(defaultLocale, format, args);
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | aae5c8ec22a1808973e5bd51ea6a1037 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class kMultipleFreeSet {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new StringTokenizer("");
TreeSet<Integer> hs = new TreeSet<>();
Integer[] a = new Integer[nxtInt()];
int k = nxtInt();
for (int i = 0; i < a.length; i++)
a[i] = nxtInt();
Arrays.sort(a);
for (int i = 0; i < a.length; i++)
if (a[i] % k != 0 || !hs.contains(a[i] / k))
hs.add(a[i]);
out.println(hs.size());
br.close();
out.close();
}
static BufferedReader br;
static StringTokenizer sc;
static PrintWriter out;
static String nxtTok() throws IOException {
while (!sc.hasMoreTokens()) {
String s = br.readLine();
if (s == null)
return null;
sc = new StringTokenizer(s.trim());
}
return sc.nextToken();
}
static int nxtInt() throws IOException {
return Integer.parseInt(nxtTok());
}
static long nxtLng() throws IOException {
return Long.parseLong(nxtTok());
}
static double nxtDbl() throws IOException {
return Double.parseDouble(nxtTok());
}
static int[] nxtIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nxtInt();
return a;
}
static long[] nxtLngArr(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nxtLng();
return a;
}
static char[] nxtCharArr() throws IOException {
return nxtTok().toCharArray();
}
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 38a5d84d125806a0414fd578ff112baf | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Sunits789
*/
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();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
long k=in.nextInt();
long arr[]=new long[n];
in.getArray(arr);
Library.sort(arr);
boolean taken[]=new boolean[n];
int c=0;
Arrays.fill(taken,false);
for(int i=0;i<n;i++){
if(!taken[i]){
int t=0;
boolean dont[]=new boolean[n];
Arrays.fill(dont,false);
for(int j=i;j<n;j++){
if(!dont[j]){
t++;
taken[j]=true;
int ind=Arrays.binarySearch(arr,k*arr[j]);
if(ind>-1){
dont[ind]=true;
}
}
}
c=Math.max(c,t);
}
}
out.println(c);
}
}
class InputReader{
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next(){
while (tokenizer == null||!tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}
catch (IOException e){
throw new RuntimeException(e);
}
catch (NullPointerException e){
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public void getArray(long arr[]){
for(int i=0;i<arr.length;i++){
arr[i]=nextLong();
}
}
}
class Library{
public static void sort(long[] n){
int len=n.length;
int l1=len/2;
int l2=len-l1;
long[] n1=new long[l1];
long[] n2=new long[l2];
for(int i=0;i<l1;i++){
n1[i]=n[i];
}
for(int i=0;i<l2;i++){
n2[i]=n[i+l1];
}
if(l1!=0){
sort(n1);
sort(n2);
}
int ind1=0;
int ind2=0;
int ind=0;
for(int i=0;i<len&&ind1<l1&&ind2<l2;i++){
if(n1[ind1]<n2[ind2]){
n[i]=n1[ind1];
ind1++;
}
else{
n[i]=n2[ind2];
ind2++;
}
ind++;
}
if(ind1<l1){
for(int i=ind1;i<l1;i++){
n[ind]=n1[i];
ind++;
}
}
if(ind2<l2){
for(int i=ind2;i<l2;i++){
n[ind]=n2[i];
ind++;
}
}
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 03b804975fd34d351308d02dc5184513 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
/**
* @param args
*/
/*
public static boolean contains(int a, int b, int c, int d)
{
return(c>= a && d <= b);
}
public static boolean isConvex(boolean[][] A)
{
boolean[] hasZero = new boolean[A.length];
int[] lo = new int[A.length];
int[] hi = new int[A.length];
for(int i = 0; i < A.length; i++)
{
int j = 0;
while(j < A[i].length && A[i][j])
j++;
if (j < A[i].length) // 0 found
{
lo[i] = j;
hasZero[i] = true;
}
while(j < A[i].length && !A[i][j]) // pasa los ceros
j++;
if (hasZero[i])
hi[i] = j - 1;
while(j < A[i].length && A[i][j]) // pasa los unos
j++;
if (j < A[i].length)
return false;
}
int j = 0;
while(j < hasZero.length && !hasZero[j])
j++;
while(j < hasZero.length && hasZero[j])
j++;
while(j < hasZero.length && !hasZero[j])
j++;
if (j < hasZero.length)
return false;
for (int i = 0; i < hasZero.length; ++i)
for (int k = i + 1; k < hasZero.length; ++k)
if (hasZero[i] && hasZero[k])
if (!contains(lo[k], hi[k], lo[i], hi[i]) && !contains(lo[i], hi[i], lo[k], hi[k]))
return false;
return true;
}
*/
public static BufferedReader scn = new BufferedReader(new InputStreamReader(System.in));
public static StringTokenizer st;
public static int nextInt() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(scn.readLine());
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException
{
int n = nextInt();
int k = nextInt();
int[] vals = new int[n];
for (int i = 0; i < n; ++i)
vals[i] = nextInt();
Arrays.sort(vals);
ArrayList<Integer> h = new ArrayList<>();
for (int i = 0; i < n; ++i)
if (h.size() > 0 && vals[i] % k == 0)
{
int lo = 0;
int hi = h.size() - 1;
int target = vals[i] / k;
//System.out.println("target " + target);
boolean found = false;
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (h.get(mid) == target)
{
found = true;
break;
}
if (h.get(mid) < target)
lo = mid + 1;
else
hi = mid - 1;
}
if (!found)
{
h.add(vals[i]);
//System.out.println("add " + vals[i]);
}
}
else
{
h.add(vals[i]);
//System.out.println("add1 " + vals[i]);
}
System.out.println(h.size());
}
// TODO Auto-generated method stub
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 6c89a56f2b5f46dd524f67e5d555e781 | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
private void solve() throws IOException {
int n = nextInt();
long k = nextLong();
long a[] = new long[n];
if (k == 1) {
println(n);
return;
}
for (int i = 0; i < n; ++i)
a[i] = nextLong();
Arrays.sort(a);
int res = n;
boolean b[] = new boolean[n];
for (int i = 0; i < n; ++i) {
if (b[i])
continue;
b[i] = true;
int t = 1;
long kk = k;
int ind = Arrays.binarySearch(a, k * a[i]);
while (ind > 0) {
b[ind] = true;
++t;
kk *= k;
ind = Arrays.binarySearch(a, kk * a[i]);
}
res = res - (t / 2);
}
println(res);
}
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
if (isFileIO) {
pw = new PrintWriter(new File("output.out"));
br = new BufferedReader(new FileReader("input.in"));
} else {
pw = new PrintWriter(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
solve();
pw.close();
br.close();
} catch (IOException e) {
System.err.println("IO Error");
}
}
private void print(Object o) {
pw.print(o);
}
private void println(Object o) {
pw.println(o);
}
private void println() {
pw.println();
}
int[] nextIntArray(int n) throws IOException {
int arr[] = new int[n];
for (int i = 0; i < n; ++i)
arr[i] = Integer.parseInt(nextToken());
return arr;
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(br.readLine());
}
return tokenizer.nextToken();
}
private BufferedReader br;
private StringTokenizer tokenizer;
private PrintWriter pw;
private final boolean isFileIO = false;
} | Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | dc341e127b19f26ac59810c80481ca4a | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author mdonaj
*/
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();
}
}
class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
long k = in.nextInt();
long[] arr = new long[n];
HashSet<Long> hs = new HashSet<Long>();
for(int i = 0; i < n; ++i)
arr[i] = in.nextInt();
Arrays.sort(arr);
int ret = 0;
for(Long i : arr) {
if(!hs.contains(i)){
hs.add(i*k);
ret++;
}
}
out.println(ret);
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 03857da9529da1eb4c0e9fae6a0279cc | train_003.jsonl | 1361374200 | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
/**
*
* @author user
*/
public class Con168_3 {
public static void main(String[] args) throws IOException {
StreamTokenizer in=new StreamTokenizer(new InputStreamReader(System.in));
long k,p;int i,j,l,m,n,c[],max,ans;boolean t[];
in.nextToken();
n=(int) in.nval;
in.nextToken();
k= (long) in.nval;
c=new int[n];
t=new boolean[n];
ans=n;
//Arrays.fill(t, false);
for(i=0;i<n;i++){
in.nextToken();
c[i]=(int) in.nval;
}
if(k==1)
{
System.out.println(n);
System.exit(0);
}
l=-1;
Arrays.sort(c);
max=c[n-1];
for(i=n-1;i>=0;i--){
p=c[i]*k;
if(p<=max){
m=(int) p;
l=Arrays.binarySearch(c, m);
if(l>=0&&!t[l]){
t[i]=true;
ans--;
}
}
}
/*for(i=0;i<n;i++){
if(!t[i])
ans++;
}*/
System.out.println(ans);
}
}
| Java | ["6 2\n2 3 6 5 4 10"] | 2 seconds | ["3"] | NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}. | Java 7 | standard input | [
"binary search",
"sortings",
"greedy"
] | 4ea1de740aa131cae632c612e1d582ed | The first line of the input contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109). The next line contains a list of n distinct positive integers a1,βa2,β...,βan (1ββ€βaiββ€β109). All the numbers in the lines are separated by single spaces. | 1,500 | On the only line of the output print the size of the largest k-multiple free subset of {a1,βa2,β...,βan}. | standard output | |
PASSED | 9dc491a61f394e6de2d76870f6e7ce59 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class TwoSubstrings {
public static void main(String args[]) throws Exception {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader s = new BufferedReader(new FileReader("*.in"));
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("*.out")));
//StringTokenizer st = new StringTokenizer(s.readLine());
String str = s.readLine();
boolean ab = false;
boolean ba = false;
int i = 1;
for(i = 1; i < str.length(); i++){
if(str.charAt(i) == 'B' && str.charAt(i-1) == 'A' && !ab){
ab = true;
i++;
break;
}
}
for(i = i+1;i<str.length(); i++){
if (str.charAt(i) == 'A' && str.charAt(i-1) == 'B' && !ba){
ba = true;
i++;
break;
}
}
if(ab && ba){
System.out.println("YES");
return;
}
if(!(ab&&ba)){
ab = false;
ba = false;
i = 1;
for(i = 1; i < str.length(); i++){
if(str.charAt(i) == 'A' && str.charAt(i-1) == 'B' && !ab){
ab = true;
i++;
break;
}
}
for(i = i+1;i<str.length(); i++){
if (str.charAt(i) == 'B' && str.charAt(i-1) == 'A' && !ba){
ba = true;
i++;
break;
}
}
}
System.out.println((ab && ba)? "YES":"NO");
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 4bd1410e32bf59235c1bd45ec81a94a1 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes |
//package javaapplication43;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
String str=scan.nextLine();
boolean flag1=false;
boolean flag2=false;
boolean flag3=false;
boolean flag4=false;
for(int i=0;i<str.length();i++){
if(!flag1&&str.charAt(i)=='A'){
if(i<str.length()-1&&str.charAt(i+1)=='B'){
flag1=true;
if(flag1&&i<str.length()-1){
++i;
}
}
}
else if(!flag2&&str.charAt(i)=='B'){
if(i<str.length()-1&&str.charAt(i+1)=='A'){
flag2=true;
if(flag2&&i<str.length()-1){
++i;
}
}
}
}
if(!flag1||!flag2){
for(int i=str.length()-1;i>=0;i--){
if(!flag3&&str.charAt(i)=='A'){
if(i>=1&&str.charAt(i-1)=='B'){
flag3=true;
if(flag3&&i>=1){
--i;
}
}
}
else if(!flag4&&str.charAt(i)=='B'){
if(i>=1&&str.charAt(i-1)=='A'){
flag4=true;
if(flag4&&i>=1){
--i;
}
}
}
}}
if(flag1&&flag2){
System.out.println("YES");
}
else if(flag3&&flag4) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 02a2390d994a5dfa2ed57f7cffebb3fe | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes |
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
/**
*
* @author a.sherif
*/
public class CodeForce {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String s = input.next();
int a = s.indexOf("AB");
int b = s.indexOf("BA");
if (s.indexOf("AB") != -1 && s.indexOf("BA") != -1 &&
( (Math.abs(s.indexOf("AB") - s.lastIndexOf("BA")) != 1) || (Math.abs(s.lastIndexOf("AB") - s.indexOf("BA")) != 1) )){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | cc34deac4c9341a26582c4633f3b8996 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | // 09/06/20 3:26 AM Jun 2020
import java.util.Scanner;
public class _550A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
if (s.contains("AB") && s.substring(s.indexOf("AB") + 2).contains("BA") || s.contains("BA") && s.substring(s.indexOf("BA") + 2).contains("AB"))
System.out.println("YES");
else
System.out.println("NO");
}
} | Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 5b50bf884adf889bd4d1d84e14ace337 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.util.*;
public class TwoSubstrings {
public static void main(String[] args) {
String s = new Scanner(System.in).next();
if(s.contains("AB") && s.replaceFirst("AB", "*").contains("BA"))
System.out.println("YES");
else if (s.contains("BA") && s.replaceFirst("BA", "*").contains("AB"))
System.out.println("YES");
else
System.out.println("NO");
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 3bde7d65820724ae58165e589ffb42a0 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.util.Scanner;
public class oveerlap {
public static void main(String[] args) {
Scanner ss = new Scanner (System.in) ;
String s = ss.next() ;
boolean f1 = false ;
boolean f2 = false ;
String t = "" ;
int c = 0 ;
int f = 0 ;
int g = 0 ;
String s2 =s ;
boolean c1 = s.contains("AB") ;
boolean c2 = s.contains("BA") ;
if (c1 && c2 ){
f = s.indexOf("A") ;
g = s.indexOf("B") ;
if (f<g)
s = s.substring(f) ;
else
s=s.substring(g) ;
for (; s.length()>=3 ;){
t = s.substring(0,2) ;
if (t.equals("AB") || t.equals("BA")){
c++ ;
s =s.substring(2);
if (t.equals("AB")){
if (s.charAt(0)=='A')
s = s.substring(1) ;
}
if (t.equals("BA")){
if (s.charAt(0)=='B')
s = s.substring(1) ;
}
}
else
s =s.substring(1);
if (c>=2)
break ;
}
}
if (s.equals("AB") || s.equals("BA")){
c++ ; }
if (c >=2)
System.out.println("YES");
else
System.out.println("NO");
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | e3b4a92c2a59b395fcc0e04c01f05896 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
private static boolean needFileIO = false;
public static void main(String[] args) {
InputStream is = System.in;
if (needFileIO) {
try {
is = new FileInputStream("in");
//os = new FileOutputStream("out");
} catch (FileNotFoundException e) { throw new RuntimeException(e); }
}
InputReader in = new InputReader(is);
OutputStream os = System.out; PrintWriter out = new PrintWriter(os);
new Solver().solve(in, out);
out.close();
}
}
class Solver {
private StringBuilder sb = new StringBuilder();
public void solve(InputReader in, PrintWriter out) {
String s = in.ns();
boolean flag1 = false, flag2 = false;
List<Integer> AB = new ArrayList<>(), BA = new ArrayList<>();
for (int i = 0; i < s.length() - 1; ++i) {
if (s.substring(i, i + 2).equals("AB")) {
AB.add(i);
}
if (s.substring(i, i + 2).equals("BA")) {
BA.add(i);
}
}
//Collections.sort(AB);
//Collections.sort(BA);
for (int i = 0; i < AB.size(); ++i) {
for (int j = 0; j < BA.size(); ++j) {
if (Math.abs(AB.get(i) - BA.get(j)) >= 2) {
flag1 = flag2 = true;
break;
}
}
}
po((flag1 && flag2) ? "YES" : "NO");
out.println(sb.toString());
}
// Short for Process Output
private void po(Object o) { sb.append("" + o).append("\n"); }
private void po(Object... o) { sb.append("" + Arrays.deepToString(o)).append("\n"); }
private void jpo(Object o) { sb.append("" + o); }
}
class InputReader {
private final BufferedReader br;
private StringTokenizer t;
public InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); t = null; }
public int ni() { return Integer.parseInt(ns()); }
public long nl() { return Long.parseLong(ns()); }
public double nd() { return Double.parseDouble(ns()); }
public BigInteger nbi() { return new BigInteger(ns()); }
public BigDecimal nbd() { return new BigDecimal(ns()); }
public String ns() {
while (t == null || !t.hasMoreTokens()) {
try { t = new StringTokenizer(br.readLine());
} catch (IOException e) { throw new RuntimeException(e); }}
return t.nextToken();
}
public String nli() {
String line = "";
try {
line = br.readLine();
} catch (IOException e) { throw new RuntimeException(e); }
return line;
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 8a236488271b1fc0e99c82e1e258a7f8 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class P550A
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word = br.readLine();
if (word.contains("AB"))
{
String word1 = word.replaceFirst("AB", "a");
if (word1.contains("BA"))
System.out.println("YES");
else if (word.contains("BA"))
{
word1 = word.replaceFirst("BA", "a");
System.out.println(word1.contains("AB") ? "YES" : "NO");
}
else
System.out.println("NO");
}
else
System.out.println("NO");
br.close();
}
} | Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 0558e5c7fcba493db77dc2ad7f1e0062 | train_003.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author walker
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.readLine();
TreeSet<Integer> AB_Set = new TreeSet<>();
TreeSet<Integer> BA_Set = new TreeSet<>();
if(s.length() == 0){
out.print("NO");
return;
}
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == 'A' && s.charAt(i + 1) == 'B'){
AB_Set.add(i);
}
if(s.charAt(i) == 'B' && s.charAt(i + 1) == 'A'){
BA_Set.add(i);
}
}
for(Integer k : AB_Set){
int x = k + 1;
int y = k - 1;
boolean b1 = BA_Set.remove(x);
boolean b2 = BA_Set.remove(y);
if(BA_Set.size() > 0){
out.print("YES");
return;
}
if(b1){
BA_Set.add(x);
}
if(b2){
BA_Set.add(y);
}
}
out.print("NO");
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
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;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 8 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | c504fc6c4c1951a460327519da2471a5 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int[] zarray(String s) {
int []z = new int[s.length()];
int l = 0, r = 0;
// z[0] = 1;
for (int i = 1; i < s.length(); i++) {
if (i <= r) {
z[i] = min(r - i + 1, z[i - l]);
}
while (i + z[i] < s.length() && s.charAt(i + z[i]) == s.charAt(z[i]))
z[i]++;
if (i + z[i] - 1 > r)
{l = i; r = i + z[i] - 1;}
}
return z;
}
public static void main(String[] args) throws Exception {
int t = 1;
// t = ni();
while (t-- > 0) {
String s = ns();
int []z = zarray(s);
int []count = new int[s.length() + 1];
for (int i : z)
count[i]++;
int c = 1;
for (int i = s.length() - 1; i >= 1; i--) {
count[i] = count[i] + count[i + 1];
}
// print(z);
for (int i = s.length() - 1; i >= 0; i--) {
if (s.length() - i == z[i]) {
ps(z[i], count[z[i]] + 1);
pln();
c++;
}
}
ps(s.length(), 1); pln();
println(c);
}
flush();
}
static Reader in = new Reader();
static StringBuilder output = new StringBuilder();
static final int imod = 1000_000_007;
static final long mod = 1000_000_007;
static final int imax = 1000_000_000;
static final int imin = -1000_000_000;
static final long lmax = 1000_000_000_000_000_000L;
static final long lmin = -1000_000_000_000_000_000L;
//input functions
static int ni() {return Integer.parseInt(in.next());}
static long nl() {return Long.parseLong(in.next());}
static String ns() {return in.next();}
static double nd() {return Double.parseDouble(in.next());}
static int[] eia(int n) {int a[] = new int[n]; return a;}
static long[] ela(int n) {long a[] = new long[n]; return a;}
static double[] eda(int n) {double a[] = new double[n]; return a;}
static String[] esa(int n) {String a[] = new String[n]; return a;}
static int[] nia(int n) {int a[] = new int[n]; for (int i = 0; i < n; i++)a[i] = ni(); return a;}
static long[] nla(int n) {long a[] = new long[n]; for (int i = 0; i < n; i++)a[i] = nl(); return a;}
static String[] nsa(int n) {String a[] = new String[n]; for (int i = 0; i < n; i++)a[i] = ns(); return a;}
static double[] nda(int n) {double a[] = new double[n]; for (int i = 0; i < n; i++)a[i] = nd(); return a;}
//output functions
static void print(String a[]) {for (String i : a) System.out.print(i + " "); System.out.println();}
static void print(int a[]) {for (int i : a) System.out.print(i + " "); System.out.println();}
static void print(long a[]) {for (long i : a) System.out.print(i + " "); System.out.println();}
static void print(double a[]) {for (double i : a) System.out.print(i + " "); System.out.println();}
static void print(Object... a) {for (Object i : a) {System.out.print(i); System.out.print(" ");} System.out.println();}
static void println(Object... a) {for (Object i : a) {System.out.print(i); System.out.print("\n");}}
static void println() {System.out.println();}
static void flush() {System.out.print(output); output = new StringBuilder();}
static void pln(int []a) {for (int i : a) {output.append(i).append('\n');}}
static void pln(long []a) {for (long i : a) {output.append(i).append('\n');}}
static void pln(double []a) {for (double i : a) {output.append(i).append('\n');}}
static void pln(String []a) {for (String i : a) {output.append(i).append('\n');}}
static void pln(Object...a) {for (Object i : a) {output.append(i).append('\n');}}
static void pln() {output.append('\n');}
static void p(int []a) {for (int i : a) {output.append(i);}}
static void p(long []a) {for (long i : a) {output.append(i);}}
static void p(double []a) {for (double i : a) {output.append(i);}}
static void p(String []a) {for (String i : a) {output.append(i);}}
static void p(Object[] a) {for (Object i : a) {output.append(i);}}
static void ps() {output.append(" ");}
static void ps(int []a) {for (int i : a) {output.append(i).append(" ");}}
static void ps(long []a) {for (long i : a) {output.append(i).append(" ");}}
static void ps(double []a) {for (double i : a) {output.append(i).append(" ");}}
static void ps(String []a) {for (String i : a) {output.append(i).append(" ");}}
static void ps(Object... a) {for (Object i : a) {output.append(i).append(" ");}}
//Utility functions
static int lowerbound(int[]a, int key) { // returns index of smallest element larger than equal to given element between indices l and r inclusive
int low = 0, high = a.length - 1, mid = (low + high) / 2; while (low < high) {if (a[mid] >= key)high = mid; else low = mid + 1; mid = (low + high) / 2;} return mid;
}
static int upperbound(int[]a, int key) {int low = 0, high = a.length - 1, mid = (low + high + 1) / 2; while (low < high) {if (a[mid] <= key) low = mid; else high = mid - 1; mid = (low + high + 1) / 2;} return mid;}
static int lowerbound(int[]a, int l, int r, int key) { int low = l, high = r, mid = (low + high) / 2; while (low < high) { if (a[mid] >= key) high = mid; else low = mid + 1; mid = (low + high) / 2;} return mid;}
static int upperbound(int[]a, int l, int r, int key) { // returns index of largest element smaller than equal to given element
int low = l, high = r, mid = (low + high + 1) / 2; while (low < high) { if (a[mid] <= key) low = mid; else high = mid - 1; mid = (low + high + 1) / 2;} return mid;
}
static long powm(long a, long b, long mod) {long an = 1; long c = a % mod; while (b > 0) {if (b % 2 == 1)an = (an * c) % mod; c = (c * c) % mod; b >>= 1;} return an;}
static long powm(long a, long b) {long an = 1; long c = a % mod; while (b > 0) {if (b % 2 == 1)an = (an * c) % mod; c = (c * c) % mod; b >>= 1;} return an;}
static long pow(long a, long b) {long an = 1; long c = a; while (b > 0) {if (b % 2 == 1)an *= c; c *= c; b >>= 1;} return an;}
static void reverse(int[]a) {for (int i = 0; i < a.length / 2; i++) {a[i] ^= a[a.length - i - 1]; a[a.length - i - 1] ^= a[i]; a[i] ^= a[a.length - i - 1];}}
static void exit() {System.exit(0);}
static int min(int... a) {int min = a[0]; for (int i : a)min = Math.min(min, i); return min;}
static long min(long... a) {long min = a[0]; for (long i : a)min = Math.min(min, i); return min;}
static double min(double... a) {double min = a[0]; for (double i : a)min = Math.min(min, i); return min;}
static double max(double... a) {double max = a[0]; for (double i : a)max = Math.max(max, i); return max;}
static int max(int... a) {int max = a[0]; for (int i : a)max = Math.max(max, i); return max;}
static long max(long... a) {long max = a[0]; for (long i : a)max = Math.max(max, i); return max;}
static long gcd(long... a) {long gcd = a[0]; for (long i : a)gcd = gcd(gcd, i); return gcd;}
static int gcd(int... a) {int gcd = a[0]; for (int i : a)gcd = gcd(gcd, i); return gcd;}
static int gcd(int a, int b) {if (b == 0)return a; if (a == 0) return b; return gcd(b, a % b);}
static long gcd(long a, long b) {if (b == 0)return a; if (a == 0) return b; return gcd(b, a % b);}
static class Pair {
long la, lb;
int a, b;
double da, db;
Pair() {} Pair(int c, int d) {a = c; b = d;}
Pair(long c, long d) {la = c; lb = d;}
Pair(int c, long d) { a = c; lb = d; }
Pair(long c, int d) { la = c; b = d; }
Pair(int c, double d) { a = c; db = d; }
Pair(double c, double d) { da = c; db = d; }
Pair(double c, int d) { da = c; b = d; }
@Override
public int hashCode() { return (a + " " + b).hashCode(); }
public boolean equals(Object c) { return (a == (((Pair)c).a) && b == (((Pair)c).b)); }
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in));
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();
}
}
}
class AL<T> extends java.util.ArrayList<T> {}
class HM<T, L> extends java.util.HashMap<T, L> {}
class HS<T> extends java.util.HashSet<T> {}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 3b359fd4fac534daef20261058e19ad6 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhas Jain
*/
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);
DPrefixesAndSuffixes solver = new DPrefixesAndSuffixes();
solver.solve(1, in, out);
out.close();
}
static class DPrefixesAndSuffixes {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
int n = s.length();
int[] lps = new int[n + 1];
for (int i = 1, j = 0; i < n; ++i) {
if (s.charAt(i) == s.charAt(j)) {
j++;
lps[i] = j;
} else {
if (j != 0) {
i--;
j = lps[j - 1];
}
}
}
lps[n] = n;
int[] ans = new int[n + 1];
for (int c : lps) ans[c]++;
for (int i = n; i > 0; --i) {
ans[lps[i - 1]] += ans[i];
}
ArrayList<String> pr = new ArrayList<>();
int pre = n;
while (pre != 0) {
pr.add(new String(pre + " " + ans[pre]));
pre = lps[pre - 1];
}
out.println(pr.size());
for (int i = pr.size() - 1; i >= 0; --i) {
out.println(pr.get(i));
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 8eeb75dc0befd89b2b474ab3fa7e7358 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.io.*;
public class D432 {
public static void main(String[] args) {
Reader in = new Reader ();
String s = in.next();
Solver t = new Solver (s);
t.process();
}
static class Solver {
char [] s;
int [] p;
ArrayList <Integer> g[];
boolean can [];
int count[];
int sub [];
Solver (String t) {
s = t.toCharArray();
p = new int [s.length];
g = new ArrayList [s.length + 10];
can = new boolean [s.length + 10];
count = new int [s.length + 10];
sub = new int [s.length + 10];
for(int i = 0; i < g.length; i++) {
g[i] = new ArrayList <Integer> ();
}
}
void prefix () {
int now = -1;
p[0] = now;
for(int i = 1; i < s.length; i++) {
while(now != -1 && s[now + 1] != s[i]) now = p[now];
if(s[now + 1] == s[i]) {
++now;
} else now = -1;
p[i] = now;
}
now = p[s.length - 1];
Arrays.fill(can, false);
while(now != -1) {
can[now] = true;
now = p[now];
}
// for(int i = 0; i < s.length; i++) {
// System.out.println (i + " " + p[i]);
// }
// System.out.println ();
}
void process() {
prefix ();
for(int i = 0; i < s.length; i++) {
int e = p[i] + 1;
int f = i + 1;
g[e].add(new Integer(f));
// System.out.println(e + " " + f);
}
for(int i = 0; i < s.length; i++) {
count[i + 1] ++;
}
dfs(0);
int ans = 1;
for(int i = 0; i < s.length; i++) ans += (can[i] ? 1 : 0);
System.out.println (ans);
for(int i = 0; i < s.length; i++) {
if(can[i] == true) {
System.out.println ((i+1) + " " + sub[i+1]);
}
}
System.out.println (s.length + " 1");
return ;
}
void dfs(int x) {
sub[x] = count[x];
for(Integer i : g[x]) {
dfs(i);
sub[x] += sub[i];
}
}
}
static class Reader {
BufferedReader a;
StringTokenizer b;
Reader () {
a = new BufferedReader (new InputStreamReader (System.in));
}
String next () {
while(b == null || !b.hasMoreTokens()) {
try {
b = new StringTokenizer (a.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return b.nextToken();
}
int nextInt() {
return Integer.parseInt(this.next());
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | ee199323506403f4e4f61a0dd6a24271 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public int[] getNext(String x) {
int len=x.length();
int[] next=new int[len+10];
int i=0;
int j=-1;
next[i]=-1;
while(i<len) {
if(j==-1||x.charAt(i)==x.charAt(j))
next[++i]=++j;
else
j=next[j];
}
return next;
}
public void solve(int testNumber, InputReader sc, PrintWriter out) {
String s=sc.next();
int[] next=getNext(s);
int[] dp=new int[s.length()+1];
Arrays.fill(dp, 1); //δ»₯iη»ε°ΎηεδΈ²εε§ε³δΈΊ1δΈͺ
ArrayList<Integer> bufLen=new ArrayList<Integer>();
for(int i=next[s.length()];i>0;i=next[i]) //ζ’δΈΊεηΌεδΈΊεηΌ
bufLen.add(i);
Collections.reverse(bufLen);
for(int i=s.length();i>=1;i--) //εηΌζ ηζζ³
dp[next[i]]+=dp[i];
out.println(bufLen.size()+1);
for(int len:bufLen)
out.println(len+" "+dp[len]);
out.println((s.length())+" "+1);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | be71aceefe712c73ca75a5d68a3d55e0 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
public class d1 extends PrintWriter {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// static Scanner s=new Scanner(System.in);
d1 () { super(System.out); }
public static void main(String[] args) throws IOException{
d1 d1=new d1 ();d1.main();d1.flush();
}
void main() throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
PrintWriter out = new PrintWriter(System.out);
// Scanner s=new Scanner(System.in);
// System.out.println(sb.length());
char[] a=s()[0].toCharArray();
zarr(a);
int[] az=Arrays.copyOf(z,z.length);
Arrays.sort(az);int n=a.length;int count=0;
for(int i=0;i<a.length;i++){
if(z[n-1-i]==i+1){
int low=0;int high=n-1;int ans=0;
while(low<=high){
int mid=(low+high)/2;
if(az[mid]>=i+1){
ans=n-mid;
high=mid-1;
}else{
low=mid+1;
}
}if(i!=0) sb.append((i+1)+" "+(ans+1)+" \n");else
sb.append((i+1)+" "+(ans)+"\n");
count++;
}
}if(n>1) {count++;sb.append(n+" "+1);}
System.out.println(count);
System.out.println(sb.toString() );
}
int[] z;
public void zarr(char[] a){
z=new int[a.length];
z[0]=1;int l=0;int r=0;
for(int i=1;i<a.length;i++){
if(i<=r){
if(i+z[i-l]-1>=r){
l=i;int j;
while(r < a.length && a[r - l] == a[r])
r++;
z[i]=r-l;
r--;
}else{
z[i]=z[i-l];
}
}else{
l=i;
r=l;int j;
while(r < a.length && a[r - l] == a[r])
r++;
z[i]=r-l;
r--;
}}
}
public void sort(int[] a,int l,int h){
if(l==h) return;
int mid=(l+h)/2;
sort(a,l,mid);
sort(a,mid+1,h);
merge(a,l,(l+h)/2,h);
}
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static String[] s() throws IOException {
return s.readLine().trim().split("\\s+");
}
static int i(String ss) {
return Integer.parseInt(ss);
}
static long l(String ss) {
return Long.parseLong(ss);
}
}
class Student {
int l;long r;
public Student(int l, long r) {
this.l = l;
this.r = r;
}
public String toString()
{
return this.l+" ";
}
}
class Pair {
int a,b;long val;int edgeVal;int max;
public Pair(int a,long val,int b,int edgeVal,int max){
this.a=a;this.b=b ; this.val=val;this.edgeVal=edgeVal;this.max=max;
}
}
class Sortbyroll implements Comparator<Student> {
public int compare(Student a, Student b){
if(a.r<b.r) return -1;
else if(a.r==b.r){
if(a.r==b.r){
return 0;
}
if(a.r<b.r) return -1;
return 1;}
return 1; }
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 39e2147c051eabb7d3b658e6c0df3daa | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeMap;
/**
* Created by omar on 11/11/17.
*/
public class Main {
static class SuffixAutomaton {
int[] link, len;
long[] occ;
TreeMap<Character, Integer>[] next;
int lst, idx;
boolean[] isLeaf;
ArrayList<Long> res = new ArrayList<>();
SuffixAutomaton(char[] s) {
int n = s.length;
link = new int[n << 1];
len = new int[n << 1];
next = new TreeMap[n << 1];
isLeaf = new boolean[n << 1];
occ = new long[n << 1];
next[0] = new TreeMap<>();
for (int i = 0; i < s.length; i++)
addLetter(s[i], i == s.length - 1);
Integer[] indices = new Integer[idx + 1];
for (int i = 0; i < idx + 1; i++)
indices[i] = i;
Arrays.sort(indices, (i1, i2) -> len[i1] - len[i2]);
for (int i = idx; i > 0; i--)
occ[link[indices[i]]] += occ[indices[i]];
int cur = 0;
for (int i = 0; i < s.length; i++) {
cur = next[cur].get(s[i]);
if (isLeaf[cur]) {
res.add(1L * i + 1);
res.add(occ[cur]);
}
}
}
ArrayList<Long> getRes() {
return res;
}
void addLetter(char c, boolean last) {
int cur = ++idx, p = lst;
occ[cur]++;
while (!next[p].containsKey(c)) {
next[p].put(c, cur);
p = link[p];
}
int q = next[p].get(c);
if (q != cur)
if (len[q] == len[p] + 1)
link[cur] = q;
else {
int clone = ++idx;
len[clone] = len[p] + 1;
link[clone] = link[q];
next[clone] = new TreeMap<>(next[q]);
link[cur] = link[q] = clone;
while (next[p].get(c) == q) {
next[p].put(c, clone);
p = link[p];
}
}
len[cur] = len[lst] + 1;
next[cur] = new TreeMap<>();
lst = cur;
if (last) {
while (cur != 0) {
isLeaf[cur] = true;
cur = link[cur];
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
char[] arr = bf.readLine().toCharArray();
SuffixAutomaton SA = new SuffixAutomaton(arr);
ArrayList<Long> res = SA.getRes();
PrintWriter out = new PrintWriter(System.out);
out.println(res.size() / 2);
for (int i = 0; i < res.size(); i += 2)
out.println(res.get(i) + " " + res.get(i + 1));
out.flush();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 82516ab14885a5978d6a2c6d9db5723b | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | //package a2oj;
import java.io.*;
import java.util.*;
public class PrefixesAndSuffixes{
// ------------------------
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// ------------------------
char[] s = sc.nextLine().toCharArray();
int n = s.length;
int[] lps = new int[n];
int ind = 1, len = 0;
while(ind < n)
if(s[ind] == s[len])
lps[ind++] = ++len;
else if(len == 0)
lps[ind++] = 0;
else
len = lps[len - 1];
int[] a = new int[n];
for(int i : lps)
a[i]++;
for(int i = n - 1; i > 0; i--)
a[lps[i - 1]] += a[i];
LinkedList<String> ll = new LinkedList<String>();
int x = lps[n - 1];
while(x != 0) {
ll.addFirst(x + " " + (a[x] + 1));
x = lps[x - 1];
}
ll.addLast(n + " 1");
out.println(ll.size());
for(String st : ll)
out.println(st);
// ------------------------
out.close();
}
//------------------------
public static PrintWriter out;
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 | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | dfa5e8dac208c5ec6f6df7cf020cdf7e | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static FastReader sc = new FastReader();
static int mod = (int) (1e9+7),MAX=(int) (2e5);
static List<Integer>[] edges;
public static int[][] parent;
public static int col = 20;
public static void main(String[] args){
String s = sc.next();
int[] pi = lps(s);
int[] freq = freq(s,pi);
List<Integer> ans = new ArrayList<>();
ans.add(s.length());
ans.add(1);
int idx = s.length()-1;
while(pi[idx] != 0) {
ans.add(pi[idx]);
ans.add(freq[pi[idx]]);
idx = pi[idx]-1;
}
out.println(ans.size()/2);
for(int i=ans.size()-1;i>=0;i-=2) {
out.println(ans.get(i-1)+" "+ans.get(i));
}
out.close();
}
static int[] lps(String s) {
int n = s.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s.charAt(i) != s.charAt(j))
j = pi[j-1];
if (s.charAt(i) == s.charAt(j))
j++;
pi[i] = j;
}
return pi;
}
static int[] freq(String s,int[] pi) {
int n = s.length();
int[] ans = new int[n+1];
for (int i = 0; i < n; i++)
ans[pi[i]]++;
for (int i = n-1; i > 0; i--)
ans[pi[i-1]] += ans[i];
for (int i = 0; i <= n; i++)
ans[i]++;
return ans;
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 828cb75bd1bcf9c35f19c53ff2f54c72 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int[] prefixFunction(char[] s) {
int n = s.length, pi[] = new int[n];
for (int i = 1, j = 0; i < n; ++i) {
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
++j;
pi[i] = j;
}
return pi;
}
static int[] zAlgo(char[] s) {
int n = s.length;
int[] z = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
r = i + z[l = i] - 1;
}
return z;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
char[] s = sc.next().toCharArray();
int n = s.length;
int[] ans = new int[n + 1];
int[] pi = prefixFunction(s);
for (int i = 0; i < n; i++)
ans[pi[i]]++;
for (int i = n - 1; i > 0; i--)
ans[pi[i - 1]] += ans[i];
for (int i = 0; i <= n; i++)
ans[i]++;
int[] z = zAlgo(s);
ArrayList<Integer> print = new ArrayList();
for (int i = 0; i < n; i++) {
int matching = z[n - i - 1];
if (matching == i + 1) {
print.add(i + 1);
print.add(ans[i + 1]);
}
}
print.add(n);
print.add(1);
out.println(print.size() >> 1);
for (int i = 0; i < print.size(); i += 2) {
out.println(print.get(i) + " " + print.get(i + 1));
}
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 22d6860fb5e3049994f675b4db9c5d99 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
int[] pref = new int[s.length()];
for (int i = 1; i < pref.length; i++) {
int j = pref[i - 1];
while (true) {
if (s.charAt(i) == s.charAt(j)) {
j++;
pref[i] = j;
break;
}
if (j <= 0) break;
j = pref[j - 1];
}
}
int[] sum = new int[s.length() + 1];
for (int i = 0; i < pref.length; i++) {
sum[pref[i]]++;
}
for (int i = pref.length - 1; i > 0; i--) {
sum[pref[i - 1]] += sum[i];
}
int pos = s.length();
int[] l = new int[s.length()];
int lLen = 0;
while (pos > 0) {
l[lLen] = pos;
lLen++;
pos = pref[pos - 1];
}
out.println(lLen);
for (int i = lLen - 1; i >= 0; i--) {
out.println(l[i] + " " + (sum[l[i]] + 1));
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 94cab8dc4b133adf537ca570961a1e6b | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class CF432D {
class Prefix {
int l, c;
public Prefix(int ll, int cc) { l = ll; c = cc; }
public String toString() { return String.format("%d %d", l, c); }
}
int[] zValues(char[] s) {
int n = s.length, L = 0, R = 0;
int[] z = new int[n];
z[0] = n;
for(int i = 1 ; i < n ; i++) {
if(i > R) {
L = R = i;
while(R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
} else {
int k = i - L;
if(z[k] < R - i + 1) {
z[i] = z[k];
} else {
L = i;
while(R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
}
}
}
return z;
}
public CF432D() {
FS scan = new FS();
PrintWriter out = new PrintWriter(System.out);
char[] s = scan.next().toCharArray();
int n = s.length;
int[] z = zValues(s);
List<Prefix> res = new ArrayList<>();
int[] suffSum = new int[n + 1];
for(int i = 0 ; i < n ; i++)
suffSum[z[i]]++;
for(int i = n - 1 ; i >= 0 ; i--)
suffSum[i] += suffSum[i + 1];
for(int i = n - 1 ; i >= 0 ; i--)
if(z[i] == s.length - i)
res.add(new Prefix(s.length - i, suffSum[z[i]]));
out.println(res.size());
for(int i = 0 ; i < res.size() ; i++)
out.println(res.get(i));
out.close();
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while(!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
}
public static void main(String[] args) { new CF432D(); }
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | a57794b965b62696eb25d22c0a7f3126 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class CF432D {
final int MAX = 200000;
final int ALPHA = 26;
int sz, last, len[], link[], trie[][];
boolean[] terminal;
void suffixAutomaton(char[] s) {
sz = 1; last = 0;
len = new int[MAX];
link = new int[MAX];
trie = new int[ALPHA][MAX];
terminal = new boolean[MAX];
link[0] = -1;
for(char cc : s) {
int c = cc - 'A';
int cur = sz++;
len[cur] = len[last] + 1;
int p = last;
while(p != -1 && trie[c][p] == 0) {
trie[c][p] = cur;
p = link[p];
}
if(p == -1) {
link[cur] = 0;
} else {
int q = trie[c][p];
if(len[p] + 1 == len[q]) {
link[cur] = q;
} else {
int clone = sz++;
len[clone] = len[p] + 1;
link[clone] = link[q];
for(int i = 0 ; i < ALPHA ; i++)
trie[i][clone] = trie[i][q];
while(p != -1 && trie[c][p] == q) {
trie[c][p] = clone;
p = link[p];
}
link[q] = link[cur] = clone;
}
}
last = cur;
}
terminal = new boolean[MAX];
int p = last;
while(p > 0) {
terminal[p] = true;
p = link[p];
}
cnt = new long[MAX];
dfs(0);
}
long[] cnt;
long dfs(int node) {
if(cnt[node] != 0)
return cnt[node];
int res = terminal[node] ? 1 : 0;
for(int let = 0 ; let < ALPHA ; let++)
if(trie[let][node] != 0)
res += dfs(trie[let][node]);
cnt[node] = res;
return res;
}
void todot() { // suffix automaton debugger
for(int i = 0 ; i < 20 ; i++)
System.out.printf("%d ", cnt[i]);
System.out.println();
System.out.println("digraph {");
System.out.println("\trankdir=LR;");
System.out.println("\tnode [shape=circle]");
System.out.println("\tedge [arrowhead=vee, penwidth=0.5, arrowsize=0.8] ");
String endStates = "";
for(int i = 0 ; i < MAX ; i++) {
if(terminal[i]) {
endStates += String.format("%d, ", i);
}
}
endStates = endStates.length() > 0 ? endStates.substring(0, endStates.length() - 2) : endStates;
System.out.printf("\t%s [shape=doublecircle]%n", endStates);
Deque<Integer> q = new ArrayDeque<>();
q.add(0);
boolean[] visited = new boolean[MAX];
visited[0] = true;
while(!q.isEmpty()) {
int node = q.pop();
for(int let = 0 ; let < ALPHA ; let++) {
if(trie[let][node] != 0) {
System.out.printf("\t%d -> %d [label=\"%c\"]%n", node, trie[let][node], ((char) (let + 'A')));
if(!visited[trie[let][node]]) {
visited[trie[let][node]] = true;
q.add(trie[let][node]);
}
}
}
}
System.out.println("}");
}
public CF432D() {
FS scan = new FS();
PrintWriter out = new PrintWriter(System.out);
char[] s = scan.next().toCharArray();
suffixAutomaton(s);
int node = 0;
List<long[]> results = new ArrayList<>();
for(int i = 0 ; i < s.length ; i++) {
int let = s[i] - 'A';
node = trie[let][node];
if(terminal[node]) {
results.add(new long[] {i + 1, cnt[node]});
}
}
out.println(results.size());
for(long[] result : results)
out.printf("%d %d%n", result[0], result[1]);
out.close();
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while(!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
}
public static void main(String[] args) { new CF432D(); }
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 26e27028051dfcfe34a4a8d7c626c9ae | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | //Codeforces
// 432-D PrefixesandSuffixes
import java.util.*;
import java.io.*;
public class Solution {
public static int[] getZArr(String s) {
int[] z = new int[s.length()];
int l = 0, r = 0;
for (int i = 1; i < s.length(); i++) {
// if within the window boundary
if (i <= r) {
z[i] = Math.min(r - i + 1, z[i - l]);
}
while ((i + z[i]) < s.length() && s.charAt(z[i]) == s.charAt(i + z[i])) {
z[i]++;
}
// to resize the window boundary
if (r < i + z[i]) {
r = i + z[i] - 1;
l = i;
}
}
return z;
}
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
String s = in.nextLine();
int[] z = getZArr(s);
z[0] = s.length();
int[] res = new int[s.length() + 1];
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < z.length; i++) {
res[z[i]]++;
if (i + z[i] == z.length)
set.add(z[i]);
}
res[s.length()] = 1;
res[0] = 0;
int prev = 1;
for (int i = s.length() - 1; i > 0; i--) {
if (res[i] != 0) {
res[i] += prev;
prev = res[i];
}
}
out.println(set.size());
for (int i : set) {
out.println(i + " " + res[i]);
}
out.close();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | d695a313516e2182f3bf72e8303b06f7 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
class GraphBuilder {
int n, m;
int[] x, y;
int index;
int[] size;
GraphBuilder(int n, int m) {
this.n = n;
this.m = m;
x = new int[m];
y = new int[m];
size = new int[n];
}
void add(int u, int v) {
x[index] = u;
y[index] = v;
size[u]++;
size[v]++;
index++;
}
int[][] build() {
int[][] graph = new int[n][];
for (int i = 0; i < n; i++) {
graph[i] = new int[size[i]];
}
for (int i = index - 1; i >= 0; i--) {
int u = x[i];
int v = y[i];
graph[u][--size[u]] = v;
graph[v][--size[v]] = u;
}
return graph;
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long[] readLongArray(int size) throws IOException {
long[] res = new long[size];
for (int i = 0; i < size; i++) {
res[i] = readLong();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Template().run();
// new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[] prefix(char[] a) {
int[] prefix = new int[a.length];
for (int i = 1; i < prefix.length; i++) {
int j = prefix[i - 1];
while (j > 0 && a[j] != a[i]) {
j = prefix[j - 1];
}
if (a[j] == a[i]) j++;
prefix[i] = j;
}
return prefix;
}
int[][] g;
int[] ans;
int[] sum;
void calc(int x, int p) {
ans[x] += sum[x];
for (int y : g[x]) {
if (y == p) continue;
calc(y, x);
ans[x] += ans[y];
}
}
void solve() throws IOException {
char[] a = readString().toCharArray();
GraphBuilder graphBuilder = new GraphBuilder(a.length + 1, a.length);
int[] prefix = prefix(a);
for (int i = 0; i < a.length; i++) {
graphBuilder.add(prefix[i], i + 1);
}
sum = new int[a.length + 1];
ans = new int[a.length + 1];
for (int x : prefix) {
sum[x]++;
}
g = graphBuilder.build();
calc(0, 0);
List<String> answer = new ArrayList<>();
int cur = a.length;
while (cur > 0) {
answer.add(cur + " " + (ans[cur] + 1));
cur = prefix[cur - 1];
}
Collections.reverse(answer);
out.println(answer.size());
for (String s : answer) {
out.println(s);
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 255364883216d59a081bbfb3be98eb31 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class _PrefixesAndSuffixes_432D
{
static int n , pi[];
static void prefixFunction(char[]s)
{
n = s.length;
pi = new int[n];
for(int i=1,j=0;i<s.length;i++)
{
while(j>0 && s[i]!=s[j])
j = pi[j-1];
if(s[i] == s[j])
++j;
pi[i] = j;
}
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
n = s.length();
int[] z = zAlgo(s.toCharArray());
int[] cum = new int[n+1];
for (int i = 1; i < z.length; i++)
if(z[i] > 0)
{
cum[1]++;
cum[z[i]+1]--;
}
for (int i = 1; i < cum.length; i++)
cum[i]+=cum[i-1];
ArrayList<Pair> arr = new ArrayList<>();
for (int i = 1; i < z.length; i++)
{
if(z[i] + i == n)
arr.add(new Pair(z[i] , cum[z[i]]+1));
}
arr.add(new Pair(s.length(),1));
PrintWriter pw = new PrintWriter(System.out);
pw.println(arr.size());
Collections.sort(arr);
for(Pair x : arr)
pw.println(x.a + " " + x.b);
pw.flush();
}
static int[] zAlgo(char[] s)
{
int n = s.length;
int[] z = new int[n];
for(int i = 1, l = 0, r = 0; i < n; ++i)
{
if(i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while(i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if(i + z[i] - 1 > r)
r = i + z[l = i] - 1;
}
return z;
}
static class Pair implements Comparable<Pair>{
int a,b;
Pair(int x, int y)
{
a=x;
b=y;
}
@Override
public int compareTo(Pair o)
{
return a-o.a;
}
}
static class Scanner{
StringTokenizer st;BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 1d1470c0359b513151c770535aff496a | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
char[] s = in.nextString().toCharArray();
int n = s.length;
int[] Z = StringUtils.ZAlgorithm(s);
int[] count = new int[n + 1];
for (int i = 1; i < n; i++) {
count[Z[i]] += 1;
}
for (int i = n; i > 0; i--) {
count[i - 1] += count[i];
}
StringBuilder ans = new StringBuilder();
int ret = 0;
for (int i = n - 1; i >= 0; i--) {
if (Z[i] + i == n) {
ret += 1;
ans.append(Z[i] + " " + (count[Z[i]] + 1) + "\n");
}
}
ret += 1;
ans.append(n + " " + 1);
out.println(ret);
out.println(ans.toString());
}
}
static class StringUtils {
public static int[] ZAlgorithm(char[] s) {
int n = s.length;
int[] z = new int[n];
int left = 0;
int right = 0;
z[0] = 0;
for (int i = 1; i < n; i++) {
if (i > right) {
left = right = i;
while (right < n && s[right - left] == s[right]) right++;
z[i] = right - left;
right--;
} else if (z[i - left] < right - i + 1) {
z[i] = z[i - left];
} else {
left = i;
while (right < n && s[right - left] == s[right]) right++;
z[i] = right - left;
right--;
}
}
return z;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 68a655a98ece0c99d36bf463be87bab7 | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class prefixSuffix {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int res=0;
char[] a=scan.next().toCharArray();
int n=a.length;
int[] z=z(a);
boolean[] match=new boolean[n];
for(int i=1;i<n;i++) {
if(z[i]==n-i) {
//prefix and suffix match
res++;
match[i]=true;
}
}
char[] db=new char[2*n+1];
for(int i=0;i<n;i++) db[i]=db[n+i+1]=a[i];
db[n]='*';
int[] dbz=z(db);
int[] f=new int[n+1];
for(int i=n+1;i<2*n+1;i++) {
f[dbz[i]]++;
}
out.println((res+1));
for(int i=n-1;i>=0;i--) f[i]+=f[i+1];
for(int i=n-1;i>=0;i--) {
if(match[i]) {
out.print(n-i);
out.print(" ");
out.print(f[n-i]);
out.println();
}
}
//special case
out.print(n);
out.print(" ");
out.print(1);
out.close();
}
public static int[] z(char[] a) {
int n=a.length;
int[] z=new int[n];
int l=0, r=0;
for(int i=1;i<n;i++) {
if (i>r) {
l=r=i;
while(r<n&&a[r-l]==a[r]) r++;
z[i]=r-l;
r--;
}
else {
int k=i-l;
if(z[k]<r-i+1) z[i]=z[k];
else {
l=i;
while(r<n&&a[r-l]==a[r]) r++;
z[i]=r-l;
r--;
}
}
}
return z;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 34050511ed1120bf417ea6f2dbf58e7c | train_003.jsonl | 1400167800 | You have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
char[] c = in.next().toCharArray();
int[] p = new int[c.length];
int k = -1;
p[0] = -1;
int[] f = new int[c.length];
for (int i = 1; i < c.length; i++) {
while (k > -1 && c[k + 1] != c[i]) k = p[k];
if (c[k + 1] == c[i]) ++k;
if (k >= 0) f[k]++;
p[i] = k;
}
int[] len = new int[c.length];
int[] count = new int[c.length];
int ac = 0;
f[c.length - 1]++;
for (int i = c.length - 1; i >= 0; i--) {
if (p[i] >= 0) {
f[p[i]] += f[i];
}
}
len[ac] = c.length;
count[ac++] = f[c.length - 1];
while (k > -1) {
len[ac] = k + 1;
count[ac++] = f[k];
k = p[k];
}
out.println(ac);
for (int i = ac - 1; i >= 0; i--) {
out.println(len[i] + " " + count[i]);
}
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.