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 | 79296c2573ffd170ab1aded0ff1f49fd | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 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));
StringTokenizer token = new StringTokenizer(br.readLine());
int n = Integer.parseInt(token.nextToken());
int k = Integer.parseInt(token.nextToken());
String str = br.readLine();
long[] arr = new long[26];
int x = str.length();
for(int i = 0; i < x; i++)
arr[str.charAt(i) - 'A']++;
Arrays.sort(arr);
long sum = 0;
for(int i = 25; i >= 0 && k > 0; i--){
if(k >= arr[i] && arr[i] != 0){
sum += arr[i] * arr[i];
k -= arr[i];
}
else if(k < arr[i] && arr[i] != 0){
sum += (long)k * k;
k = 0;
}
}
System.out.println(sum);
}
} | Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | 8b7fce711ef0fbd0563f3385c8253f8a | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Mario {
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();
long c=cin.nextLong();
long arr[]=new long[26];
String s=cin.next();
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i)-'A']++;
}
Arrays.sort(arr);
long sum=0;
for (int i = arr.length-1; i >=0; i--) {
if(arr[i]>=c) {
sum+=c*c;
break;
}else
{
sum+=arr[i]*arr[i];
c-=arr[i];
}
}
System.out.println(sum);
}
} | Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | 1822fd4247b183735692c644f7bb2018 | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 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.StringTokenizer;
public class Solve {
void sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
System.out.print(i + " ");
}
}
static void solve(long n, PrintWriter out) {
ArrayList<Long> arr = new ArrayList<Long>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (arr.size() > 3) {
out.println("NO");
return;
}
if (n % i == 0) {
if (n / i == i)
arr.add(i);
else {
arr.add(i);
arr.add(n / i);
}
}
}
if (arr.size() == 3)
out.println("YES");
else
out.println("NO");
}
/**
* @param args
* @throws NumberFormatException
* @throws IOException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
RizkScanner sc = new RizkScanner();
PrintWriter out = new PrintWriter(System.out);
// RizkScanner sc = new RizkScanner("input.txt");
// PrintWriter out = new PrintWriter("output.txt");
int n = sc.nextInt();
long k = sc.nextLong();
String s = sc.next();
long[] arr = new long[256];
for (int i = 0; i < s.length(); i++)
arr[s.charAt(i)]++;
Arrays.sort(arr);
int i = 255;
long answer = 0;
while (k > 0) {
if (arr[i] <= k) {
k -= arr[i];
answer += (arr[i] * arr[i]);
} else {
answer += (k * k);
k = 0;
}
i--;
}
out.print(answer);
out.flush();
}
static class RizkScanner {
BufferedReader br;
StringTokenizer st;
RizkScanner(String file) throws IOException {
br = new BufferedReader(new FileReader(new File(file)));
}
RizkScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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 NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
float nextFloat() throws NumberFormatException, IOException {
return Float.parseFloat(next());
}
}
} | Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | 385f54806439ff953c7135e4908dfa1b | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes | import java.math.BigInteger;
import java.util.Collections;
import java.util.Scanner;
public class B_462 {
public static long[] merge_sort(long[] input,int start,int end)
{
int mid=(start+end)/2;
if(start>end)
return new long[0];
if(start==end) {
long[] arr=new long[1];
arr[0]=input[start];
return arr;
}
;
long[] pre=merge_sort(input, start, mid);
long[] post=merge_sort(input,mid+1,end);
int i,j;
long[] merge=new long[pre.length + post.length];
i=j=0;
int index=0;
while(i<pre.length && j<post.length) //merging
{
if(pre[i]<post[j])
{
merge[index++]=pre[i++];
}
else if(pre[i]>post[j])
{
merge[index++]=post[j++];
}
else if(pre[i]==post[j])
{
merge[index++]=pre[i++];
merge[index++]=post[j++];
}
}
while(j<post.length)
{
merge[index++]=post[j++];
}
while(i<pre.length)
{
merge[index++]=pre[i++];
}
return merge;
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int k=s.nextInt();
s.nextLine();
String input=s.nextLine();
//System.out.println(input.length());
long[] countArr=new long[91];
for(int i=0;i<input.length();i++)
{
int asciiVal=input.charAt(i);
countArr[asciiVal]++;
}
long remainingCards=k;
long ans=0;
int index=countArr.length-1;
long[] sortedArray=merge_sort(countArr, 0, countArr.length-1);
while(index>=65 && sortedArray[index]>0 && remainingCards>0)
{
long cardstaken=0;
if(sortedArray[index]<remainingCards )
{
cardstaken=sortedArray[index];
ans=ans+cardstaken*cardstaken;
remainingCards=remainingCards-cardstaken;
index--;
//System.out.println(cardstaken + " " + remainingCards + " " +ans );
}
else if(sortedArray[index]>=remainingCards)
{
cardstaken=remainingCards;
ans=ans+cardstaken*cardstaken;
//System.out.println(cardstaken + " " + remainingCards + " " +ans );
break;
}
}
System.out.println(ans);
}
}
| Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | 12c7279bd87fc6fec20d911c299a548c | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes | import java.util.*;
public class ForceCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long k = (long) scanner.nextInt();
String str = scanner.next();
long[] count = new long[26];
for (int i = 0; i < n; i++){
count[str.charAt(i)-'A'] ++;
}
Arrays.sort(count);
long res = 0;
for (int i = 25; i >= 0; i--){
if (k > count[i]){
res += count[i]*count[i];
k -= count[i];
}else{
res += k*k;
break;
}
}
System.out.println(res);
}
}
| Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | 94628fd009f0086aa13ef0351b1d1ecb | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes |
import java.util.Arrays;
import static java.util.Arrays.fill;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
/**
*
* @author nirmit
*/
public class Main1 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
Integer a[]=new Integer[26];
fill(a,0);
String s=sc.next();
for(int i=0;i<n;i++)
{
char ch=s.charAt(i);
int l=(int)ch-'A';
a[l]++;
}
long sum=0;
Arrays.sort(a , new reverse());
for(int i=0;a[i]!=0 && i<26;i++)
{
if(k<a[i])
{
//if(a[i+1]==0 || i==25)
{
sum+= (long)k*k;
k=0;
break;
}
}
else
{
sum+=(long)a[i]*a[i];
k-=a[i];
}
if(k==0)
break;
}
System.out.print(sum);
}
}
class reverse implements Comparator<Integer>
{
public int compare(Integer k,Integer k1)
{
if(k>k1)
return -1;
else if(k<k1)
return 1;
return 0;
}
} | Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | c0fe83e81aeb133b2b97e170fb503d3b | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes | import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.Collections;
import java.util.Comparator;
import java.io.PrintWriter;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
long k = sc.nextLong();
String in = sc.next();
long arr[] = new long[200];
for(int i=0;i<n;i++)
{
arr[in.charAt(i)]++;
}
ArrayList<Long> value = new ArrayList<>();
for(int i=65;i<=92;i++)
if(arr[i]!=0)
value.add(arr[i]);
Collections.sort(value,Collections.reverseOrder());
long cnt =0;
for(long x:value)
{
if(k>=x)
{
k-=x;
cnt+=x*x;
}
else
{
cnt += k*k;
k=0;
break;
}
}
out.println(cnt);
out.flush();
}
} | Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | e9d29f4a2f3910ca2953ed0fe3b4c8a8 | train_003.jsonl | 1409061600 | Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? | 256 megabytes |
import java.util.*;
public class MA {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n =scan.nextInt();
long k = scan.nextInt();
String s = scan.next();
int arr [] = new int[26];
for(int i=0;i<s.length();i++) {
char a = s.charAt(i);
int val = a-'A';
arr[val]++;
}
long max = Integer.MIN_VALUE;
long count=0;
while(k>0) {
int temp=0;
for(int i=0;i<26;i++) {
if(max<arr[i]) {
max = arr[i];
temp =i;
}
}
if(max>k)
count +=(k*(k));
else {
count += max*max;
}
k = k-max;
arr[temp] =0;
max =Integer.MIN_VALUE;
}
System.out.println(count);
}
}
| Java | ["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"] | 1 second | ["82", "4"] | NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin. | Java 8 | standard input | [
"greedy"
] | 480defc596ee5bc800ea569fd76dc584 | The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n uppercase letters without spaces β the i-th letter describes the i-th card of the Appleman. | 1,300 | Print a single integer β the answer to the problem. | standard output | |
PASSED | bb8f33af1ec119e9c3e5bdb98e883dc7 | train_003.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ Β β are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.function.*;
import java.util.stream.*;
import java.util.stream.Collectors;
public class E {
private static final FastReader in = new FastReader();
private static final FastWriter out = new FastWriter();
public static void main(String[] args) {
new E().run();
}
private void run() {
var t = 1;
while (t-- > 0) {
solve();
}
out.flush();
}
boolean[][] visited;
int n, m, g;
int[] d;
boolean newVisit;
long visitN = Long.MAX_VALUE;
private void solve() {
n = in.nextInt();
m = in.nextInt();
d = in.nextIntArray(m);
g = in.nextInt();
var r = in.nextInt();
ArrayUtils.sort(d);
d = Arrays.stream(d).distinct().toArray();
m = d.length;
visited = new boolean[m][];
for (var i = 0; i < m; i++) {
visited[i] = new boolean[g + 1];
}
visited[0][0] = true;
for (var k = 0; ; k++) {
newVisit = false;
var nextV = new ArrayList<Integer>();
for (var i = 0; i < m; i++) {
if (visited[i][0]) {
nextV.add(i);
}
}
nextV.forEach(x -> walk(x, 0));
if (visitN < Long.MAX_VALUE) {
visitN += (long) k * (g + r);
break;
}
if (!newVisit) {
break;
}
}
out.println(visitN == Long.MAX_VALUE ? -1 : visitN);
}
void walk(int x, int t) {
if (d[x] == n) {
visitN = Math.min(visitN, t);
return ;
}
if (t == g) {
visited[x][0] = true;
return ;
}
if (d[x] < n) {
var dd = d[x + 1] - d[x];
if (t + dd <= g && !visited[x + 1][t + dd]) {
newVisit = true;
visited[x + 1][t + dd] = true;
walk(x + 1, t + dd);
}
}
if (d[x] > 0) {
var dd = d[x] - d[x - 1];
if (t + dd <= g && !visited[x - 1][t + dd]) {
newVisit = true;
visited[x - 1][t + dd] = true;
walk(x - 1, t + dd);
}
}
}
}
class ArrayUtils {
public static int[] of(int n, int defaultValue) {
var a = new int[n];
Arrays.fill(a, defaultValue);
return a;
}
public static long[] of(int n, long defaultValue) {
var a = new long[n];
Arrays.fill(a, defaultValue);
return a;
}
public static int max(int[] a) {
return Arrays.stream(a).max().getAsInt();
}
public static long max(long[] a) {
return Arrays.stream(a).max().getAsLong();
}
public static <T extends Comparable<? super T>> T max(T[] a) {
return Collections.max(Arrays.asList(a));
}
public static int min(int[] a) {
return Arrays.stream(a).min().getAsInt();
}
public static long min(long[] a) {
return Arrays.stream(a).min().getAsLong();
}
public static <T extends Comparable<? super T>> T min(T[] a) {
return Collections.max(Arrays.asList(a));
}
public static void sort(int[] a) {
var al = Arrays.stream(a).boxed().collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(al);
Collections.sort(al);
for (var i = 0; i < a.length; i++) {
a[i] = al.get(i);
}
}
public static void sort(long[] a) {
var al = Arrays.stream(a).boxed().collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(al);
Collections.sort(al);
for (var i = 0; i < a.length; i++) {
a[i] = al.get(i);
}
}
public static void reverse(int[] a) {
for (int l = 0, r = a.length - 1; l <= r; l++, r--) {
var t = a[l];
a[l] = a[r];
a[r] = t;
}
}
public static void reverse(long[] a) {
for (int l = 0, r = a.length - 1; l <= r; l++, r--) {
var t = a[l];
a[l] = a[r];
a[r] = t;
}
}
}
class FastReader {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer in;
public String next() {
while (in == null || !in.hasMoreTokens()) {
try {
in = new StringTokenizer(br.readLine());
} catch (IOException e) {
return null;
}
}
return in.nextToken();
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public boolean nextBoolean() {
return Boolean.valueOf(next());
}
public byte nextByte() {
return Byte.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
public double[] nextDoubleArray(int length) {
var a = new double[length];
for (var i = 0; i < length; i++) {
a[i] = nextDouble();
}
return a;
}
public int nextInt() {
return Integer.valueOf(next());
}
public int[] nextIntArray(int length) {
var a = new int[length];
for (var i = 0; i < length; i++) {
a[i] = nextInt();
}
return a;
}
public long nextLong() {
return Long.valueOf(next());
}
public long[] nextLongArray(int length) {
var a = new long[length];
for (var i = 0; i < length; i++) {
a[i] = nextLong();
}
return a;
}
}
class FastWriter extends PrintWriter {
public FastWriter() {
super(System.out);
}
public void println(boolean[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(double[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(int[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(long[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(Object... a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public <T> void println(List<T> l) {
println(l.toArray());
}
public void debug(String name, Object o) {
String value = Arrays.deepToString(new Object[] { o });
value = value.substring(1, value.length() - 1);
System.err.println(name + " => " + value);
}
}
| Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: Β Β Β Β for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. Β Β Β Β for the second green light reaches $$$14$$$. Wait for the red light again. Β Β Β Β for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 11 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ Β β road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ Β β the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ Β β the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer Β β the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | fa8e4f5145b48d5e6967dfd812791a9d | train_003.jsonl | 1587653100 | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ Β β are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public void solve() {
int n = reader.nextInt();
int m = reader.nextInt();
int[] d = new int[m];
for (int i = 0; i < m; i++) d[i] = reader.nextInt();
int g = reader.nextInt();
int r = reader.nextInt();
writer.println(find(n, m, d, g, r));
}
void sort(int[] d, int m) {
Random random = new Random();
for (int i = 1; i < m; i++) {
int j = random.nextInt(i);
int tmp = d[i];
d[i] = d[j];
d[j] = tmp;
}
Arrays.sort(d);
}
long find(int n, int m, int[] d, int g, int r) {
sort(d, m);
boolean[][] vst = new boolean[m][g + 1];
Vertex start = new Vertex(0, g, 0);
vst[start.island][start.remain] = true;
Deque<Vertex> queue = new ArrayDeque<>(m);
queue.add(start);
long res = Long.MAX_VALUE;
while (!queue.isEmpty()) {
Vertex now = queue.poll();
if (now.island == m-1) continue;
if (now.remain == g && n - d[now.island] <= now.remain) {
res = Math.min(res, now.dist * (r + g) + n - d[now.island]);
}
for (int i = +1; i >= -1; i -= 2) {
Vertex next = new Vertex(now.island + i, 0, now.dist);
if (next.island < 0 || next.island >= m-1) continue;
int time = Math.abs(d[now.island] - d[next.island]);
if (time > now.remain) continue;
next.remain = now.remain - time;
if (vst[next.island][next.remain]) continue;
vst[next.island][next.remain] = true;
if (next.remain == 0) {
next.remain = g;
next.dist++;
queue.addLast(next);
} else {
queue.addFirst(next);
}
}
}
return res == Long.MAX_VALUE ? -1 : res;
}
static class Vertex {
int island;
int remain;
int dist;
public Vertex(int island, int remain, int dist) {
this.island = island;
this.remain = remain;
this.dist = dist;
}
}
private InputReader reader;
private PrintWriter writer;
public Solution(InputReader reader, PrintWriter writer) {
this.reader = reader;
this.writer = writer;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out);
Solution solution = new Solution(reader, writer);
solution.solve();
writer.flush();
}
static class InputReader {
private static final int BUFFER_SIZE = 1 << 20;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| Java | ["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"] | 1 second | ["45", "-1"] | NoteIn the first test, the optimal route is: Β Β Β Β for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. Β Β Β Β for the second green light reaches $$$14$$$. Wait for the red light again. Β Β Β Β for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules. | Java 11 | standard input | [
"implementation",
"graphs",
"shortest paths"
] | 64625b26514984c4425c2813612115b3 | The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ Β β road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ Β β the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ Β β the time that the green light stays on and the time that the red light stays on. | 2,400 | Output a single integer Β β the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$. | standard output | |
PASSED | c0a07266004dd929379999cf846cedd4 | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(in, out);
out.close();
}
}
class TaskC {
private StringBuffer result = new StringBuffer("");
private boolean flag = false;
public void solve(InputReader in, OutputWriter out) {
int t = in.nextInt();
calculate(in);
if(flag || in.hasNext()) {
out.printLine("Error occurred");
} else {
out.printLine(result.toString());
}
}
private void calculate(InputReader in) {
if(in.hasNext()) {
String word = in.next();
if(word.equals("pair")) {
result.append("pair<");
calculate(in);
result.append(",");
calculate(in);
result.append(">");
} else {
result.append("int");
}
} else {
flag = true;
}
}
}
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 boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if ( line == null ) {
return false;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() { return Double.parseDouble(next());}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if ( i != 0 ) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | fc042dc5f6dde0a7f9be3d27e083c7b0 | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C190
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n;
static String s;
static String[] words;
static StringBuilder sb=new StringBuilder();
static boolean error=false;
static int found=0;
public static int recover(int i)
{
if(i>=words.length || error)
{
error=true;
return i;
}
found++;
if(words[i].equals("int"))
{
sb.append("int");
return i;
}
else
{
sb.append("pair<");
int idx=recover(i+1)+1;
sb.append(",");
idx=recover(idx);
sb.append(">");
return idx;
}
}
public static void main(String[] args)
{
n=in.nextInt();
s=in.nextLine();
words=s.split(" ");
recover(0);
if(found!=words.length || error)
{
out.println("Error occurred");
}
else
{
out.println(sb.toString());
}
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | 2c624f8aff267fcc7dd153d17f71b906 | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C190
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n;
static String s;
static String[] words;
static StringBuilder sb=new StringBuilder();
static boolean error=false;
static int found=0;
public static int recover(int i)
{
if(i>=words.length || error)
{
error=true;
return i;
}
found++;
if(words[i].equals("int"))
{
sb.append("int");
return i;
}
else
{
sb.append("pair<");
int idx=recover(i+1);
sb.append(",");
idx=recover(idx+1);
sb.append(">");
return idx;
}
}
public static void main(String[] args)
{
n=in.nextInt();
s=in.nextLine();
words=s.split(" ");
recover(0);
if(found!=words.length || error)
{
out.println("Error occurred");
}
else
{
out.println(sb.toString());
}
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | a1b3fb0fce6ab860a6690b8f28d6aa53 | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static String[] words;
static StringBuilder sb = new StringBuilder();
static int found;
static boolean error;
static int recover(int idx)
{
if(idx >= words.length)
{
error = true;
return idx;
}
++found;
if(words[idx].equals("int"))
{
sb.append("int");
return idx;
}
sb.append("pair<");
int nxtIdx = recover(idx + 1) + 1;
sb.append(",");
nxtIdx = recover(nxtIdx);
sb.append(">");
return nxtIdx;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
words = sc.nextLine().split(" ");
recover(0);
if(error || found != words.length)
out.println("Error occurred");
else
out.println(sb);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | 2e80f80a36e0cdb24c42349fbc0229b4 | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P190C {
StringBuilder ans = new StringBuilder();
Deque<String> inp = new ArrayDeque();
boolean parse() {
if (inp.size() == 0) {
return false;
}
if (inp.pollFirst().equals("int")) {
ans.append("int");
} else {
ans.append("pair<");
if (!parse()) { return false; }
ans.append(',');
if (!parse()) { return false; }
ans.append('>');
}
return true;
}
public void run() throws Exception {
next(); //skip 'n'
for (String s : nextLine().split(" ")) {
inp.addLast(s);
}
println((parse() && (inp.size() == 0)) ? ans : "Error occurred");
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P190C().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
} | Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | bc1285250d06c29b1963cff61745836a | train_003.jsonl | 1337182200 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform. | 256 megabytes | import java.util.Scanner;
public class Main {
static Scanner scan;
static String s;
static StringBuilder res = new StringBuilder("");
static boolean fail = false;
public static void main(String[] args) {
scan = new Scanner(System.in);
String n = scan.nextLine();
recur();
if (fail || scan.hasNext())
System.out.println("Error occurred");
else
System.out.println(res.toString());
}
private static void recur() {
if (scan.hasNext()) {
s = scan.next();
res.append(s);
if (s.equals("pair")) {
res.append("<");
recur();
res.append(",");
recur();
res.append(">");
}
}
else
fail = true;
}
} | Java | ["3\npair pair int int int", "1\npair int"] | 2 seconds | ["pair<pair<int,int>,int>", "Error occurred"] | null | Java 8 | standard input | [
"dfs and similar"
] | 6587be85c64a0d5fb66eec0c5957cb62 | The first line contains a single integer n (1ββ€βnββ€β105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int". | 1,500 | If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values. | standard output | |
PASSED | a78b3c75cd434654bd7657b8fdfbb4e8 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int d=sc.nextInt();
int marks=a+b+c+d;
int rank=1;
for(int i=2;i<=n;i++)
{
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
int s=a+b+c+d;
if(s>marks)
rank++;
}
System.out.print(rank);
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | fa631bdac2bd206d6fbd867ba758d1b3 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 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 NicolaiNisbeth
*/
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);
TheRank solver = new TheRank();
solver.solve(1, in, out);
out.close();
}
static class TheRank {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int place = 1;
int t = in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt();
for (int i = 1; i < n; i++) {
int s = in.nextInt() + in.nextInt() + in.nextInt() + in.nextInt();
if (s > t) place++;
}
out.print(place);
}
}
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\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 39cfbf3c3093cf302361dbb5a3bb1319 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class A1017_Rank {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int rank = 1;
int Thomas = scan.nextInt() + scan.nextInt() + scan.nextInt() + scan.nextInt();
for (int i = 1; i < n; i++) {
int grade = scan.nextInt() + scan.nextInt() + scan.nextInt() + scan.nextInt();
if (Thomas < grade) rank++;
}
System.out.println(rank);
}
}
| Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | e405964de4e87a789df400efc4c59327 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.*;
import java.io.*;
public class A {
public static void main(String args[]) {
FastScanner in=new FastScanner();
// int t=in.nextInt();
// L: while(--t>=0) {
int n=in.nextInt();
ArrayList<int []> arr=new ArrayList<>();
for(int i=0;i<n;i++) {
arr.add(new int[] {i, in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt()});
}
Collections.sort(arr, (x, y)->y[1]+y[2]+y[3]+y[4]-x[1]-x[2]-x[3]-x[4]);
for(int i=0;i<n;i++) {
// System.out.println(Arrays.toString(arr.get(i)));
if(arr.get(i)[0]==0)
System.out.println(i+1);
}
// }
}
///////////////////////////
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | cdc42d4381cc0a3e2e22807ac135967b | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.*;
public class mohammad{
public static void main(String args[]){
Scanner U = new Scanner(System.in);
int t = U.nextInt();
int[] b= new int[t];
for(int i=0 ; i<t ; i++){
int[] a= new int[4];
for(int j=0 ; j<4 ; j++)
a[j]= U.nextInt();
int sum = 0;
for(int j=0 ; j<4 ; j++)
sum+=a[j];
b[i] = sum;
}
int k=t;
for(int i=1;i<t;i++){
if (b[0]>=b[i])
k--;
}
System.out.println(k);
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 913503cd4979d9cccc88ab42f2a5faec | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class Lo
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int sum=0;
int c=1;
int max=0;
int E = s.nextInt();
int G = s.nextInt();
int M = s.nextInt();
int H = s.nextInt();
max =E+G+M+H;
for(int i=2;i<=n;i++)
{
E = s.nextInt();
G = s.nextInt();
M = s.nextInt();
H = s.nextInt();
sum = E+G+M+H;
if(sum>max)
{
//max = sum;
c++;
}
}
System.out.println(c);
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 40edb6e952d2214b315b74ac86f8da17 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import static java.util.Arrays.sort;
import java.util.Scanner;
public class Domilson {
public static void main(String[] args) {
Scanner ler=new Scanner(System.in);
int i,j,a,s=0;
int n=ler.nextInt();
int lugar[]=new int [n];
for(i=1;i<=n;i++){
for(j=0;j<4;j++){
a=ler.nextInt();
lugar[i-1]-=a;
}
if(i==1)s=lugar[i-1];
}
sort(lugar);
for(i=0;i<n;i++){
if(s==lugar[i])break;
}
System.out.println((i+1));
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 369e4ff66c4478b0238b18f73d3da537 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
import java.util.stream.Stream;
public class TheRank {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int rank=1;
int [] num=new int[n];
for (int i = 0; i < n; i++) {
int temp=0;
int[] line= Stream.of(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
for(double x:line){temp+=x;}
num[i]=temp;
}
int tem=num[0];
for (int i = 1; i < n; i++) {
if (tem<num[i])rank++;
}
System.out.println(rank);
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 521d7ff39bbd5e9ab60fbf4bdc88ea32 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n,a,b,c,d;
int pos =1;
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
int sum1 = a+b+c+d;
for(int i=2;i<=n;++i){
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
int sum = a+b+c+d;
if(sum>sum1){
pos++;
}
}
System.out.println(pos);
}
}
| Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 4d5940b21d056a7f20b8db73d89b8294 | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] a=new int[n+1][2];
for(int i=1;i<=n;i++)
{
a[i][0]=i;
for(int j=0;j<4;j++)
{
a[i][1]+=sc.nextInt();
}
}
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(a[i][1]<a[j][1])
{
int tempa=a[i][0];
int tempb=a[i][1];
a[i][0]=a[j][0];
a[i][1]=a[j][1];
a[j][0]=tempa;
a[j][1]=tempb;
}
else if(a[i][1]==a[j][1] && a[i][0]>a[j][0])
{
int temp=a[i][0];
a[i][0]=a[j][0];
a[j][0]=temp;
}
}
}
for(int i=1;i<=n;i++)
{
if(a[i][0]==1)
{
System.out.println(i);
break;
}
}
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 102b134534d77860701819b0eafedf7b | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Codeforces3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long b,k=0, c = 0, a = input.nextLong();
long[] e= new long[1000];
if (a > 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j < 4; j++) {
b = input.nextLong();
c += b;
}
e[i]=c;
if(i==0)
{
k=c;
}
c = 0;
}
Arrays.sort(e);
for(int i=999;i>=1000-a;i--)
{
if(e[i]==k)
{
System.out.println(1000-i);
break;
}
}
} else {
System.out.println("1");
}
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 56c121db87453cdce0e57209bf492cef | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
import javafx.util.converter.BigIntegerStringConverter;
import java.util.*;
/**
*
* @author Ahmad
*/
public class JavaApplication1 {
public static void main (String[] args) throws IOException, Exception {
FastReader console = new FastReader();
int n = console.nextInt() ;
int x[] = new int [n] ;
int s = 0 ;
for (int i=0 ; i<4 ; i++){
s+=console.nextInt();
}
x[0]=s ;
int ind = 1 ;
for (int i=0 ; i<n-1 ; i++){
int sum = 0 ;
for (int j=0 ; j<4 ; j++){
sum+=console.nextInt() ;
}
x[ind]=sum ;
ind++ ;
}
Sorting.bucketSort(x, n) ;
int count = 1 ;
for (int i=x.length-1 ; i>=0 ; i--){
if (x[i]==s){
System.out.println(count);
break ;
}
else {
count ++ ;
}
}
}
}
class Sorting{
public static int[] bucketSort(int[] array, int bucketCount) {
if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count");
if (array.length <= 1) return array; //trivially sorted
int high = array[0];
int low = array[0];
for (int i = 1; i < array.length; i++) { //find the range of input elements
if (array[i] > high) high = array[i];
if (array[i] < low) low = array[i];
}
double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket
ArrayList<Integer> buckets[] = new ArrayList[bucketCount];
for (int i = 0; i < bucketCount; i++) { //initialize buckets
buckets[i] = new ArrayList();
}
for (int i = 0; i < array.length; i++) { //partition the input array
buckets[(int)((array[i] - low)/interval)].add(array[i]);
}
int pointer = 0;
for (int i = 0; i < buckets.length; i++) {
Collections.sort(buckets[i]); //mergeSort
for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets
array[pointer] = buckets[i].get(j);
pointer++;
}
}
return array;
}
}
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 | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 69540458eb2f5196be775012059c0b2f | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class TheRank {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r = sc.nextInt() + 1;
int c = 5;
int[][] m = new int[r][c];
int othersSum = 0;
int tomasSum = 0;
int tomasRank = r;
for (int i = 1; i < r; i++) {
for (int j = 1; j < c; j++) {
m[i][j] = sc.nextInt();
if (i == 1)
tomasSum += m[1][j];
else
othersSum += m[i][j];
}
if (tomasSum >= othersSum)
tomasRank--;
othersSum = 0;
}
System.out.print(tomasRank);
sc.close();
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 94669cbb0d80b1fc49c506e88620c74c | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | /*
Problem Name: The Rank
URL: http://codeforces.com/problemset/problem/1017/A
*/
import java.util.*;
public class The_Rank{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] sum = new int[n-1];
int johnSum = 0;
for(int i = 0;i<n;i++){
for(int j = 0;j<4;j++){
int num = sc.nextInt();
if(i!=0){
sum[i-1]+=num;
}else{
johnSum+=num;
}
}
}
Arrays.sort(sum);
int[] reverse = new int[n-1];
for(int i = 0, j = n-2;i<n-1;i++,j--){
reverse[i] = sum[j];
}
boolean flag = true;
for(int i = 0;i<n-1;i++){
if(johnSum>=reverse[i]){
System.out.println(i+1);
flag = false;
break;
}
}
if(flag){
System.out.println(n);
}
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 21262618a0cdd5d7ef62815d2120a65e | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;
public class DONEMestoVTablice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a, b, c, d;
int[] arr = new int[n];
int index = 0;
int Tomsum = 0;
int Tomindex = -1;
for (int i = 0; i < n; i++) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
arr[index++] = a + b + c + d;
}
Tomsum = arr[0];
sort(arr);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == Tomsum) {
Tomindex = i;
break;
}
}
System.out.println(Tomindex +1);
}
public static void sort(int[] arr) {
for (int begin = 0; begin < arr.length; begin++) {
maxToBegin(arr, begin);
}
}
private static void maxToBegin(int[] arr, int begin) {
int indexMax = getMaxInRange(arr, begin, arr.length);
swap(arr, indexMax, begin);
}
private static void swap(int[] arr, int i, int j) {
int pocket = arr[i];
arr[i] = arr[j];
arr[j] = pocket;
}
private static int getMaxInRange(int[] arr, int from, int to) {
int max = from;
for (int i = from; i < arr.length; i++) {
if (arr[i] > arr[max]) {
max = i;
}
}
return max;
}
} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 045253bf064fad87b850722482182dba | train_003.jsonl | 1533737100 | John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. | 256 megabytes | import java.util.Scanner;import java.util.Arrays;
public class ranking {
public static void main (String [] args) {
Scanner scanner = new Scanner (System.in);
int n=scanner.nextInt();
int [] a;a=new int [n];
int [] b;b=new int [n];
for (int i=0;i<n;i++) {
for (int j=0;j<4;j++) {
int x=scanner.nextInt();
a[i]+=x;
}
b[i]=a[i];
}
Arrays.sort(a);
int r=0;
for (int i=0;i<n;i++) {
if (a[i]==b[0]) r=i;
}
System.out.println(n-r);
scanner.close(); }} | Java | ["5\n100 98 100 100\n100 100 100 100\n100 100 99 99\n90 99 90 100\n100 98 60 99", "6\n100 80 90 99\n60 60 60 60\n90 60 100 60\n60 100 60 80\n100 100 0 100\n0 0 0 0"] | 1 second | ["2", "1"] | NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$. | Java 8 | standard input | [
"implementation"
] | 3c984366bba580993d1694d27982a773 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$)Β β the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$. | 800 | Print the rank of Thomas Smith. Thomas's id is $$$1$$$. | standard output | |
PASSED | 8e4cc7d128f050504f5295ab133acb8e | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
public class B129 {
static int[] neg;
static Set<Integer> curr;
static int grp;
private static void get1(int n) {
for (int i = 1; i <= n; i++) {
if (neg[i] == 1) {
curr.add(i);
neg[i] = 0;
}
}
if (curr.size() > 0)
grp++;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
grp = 0;
Map<Integer, List<Integer>> adjList = new HashMap<>();
curr = new HashSet<>();
int[] vi = new int[n + 1];
neg = new int[n + 1];
for (int i = 1; i <= n; i++)
adjList.put(i, new LinkedList<>());
while (m-- > 0) {
int x = sc.nextInt();
int y = sc.nextInt();
adjList.get(x).add(y);
adjList.get(y).add(x);
neg[x] += 1;
neg[y] += 1;
}
sc.close();
for (int i = 1; i <= n; i++) {
get1(n);
for (int node : curr) {
if (vi[node] == 0) {
vi[node] = 1;
for (int negh : adjList.get(node))
neg[negh] -= 1;
}
}
curr.clear();
}
System.out.println(grp);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 2f127dfde4093a57780249c353a07329 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
/*
.
.
.
.
.
.
.
some constants
.
*/
static int i=0,j=0,k=0,l=0;
/*
.
.
.
if any
.
.
*/
public static void main(String[] args) throws IOException{
/*
.
.
.
.
.
.
*/
int n=ni();
int m=ni();
boolean removed[]=new boolean[n+1];
List<Integer> g[]=new ArrayList[n+1];
for(i=1;i<=n;i++)
g[i]=new ArrayList<>();
while(m-->0){
int u=ni();
int v=ni();
g[u].add(v);
g[v].add(u);
}
int cnt=-1;
List<Integer> rem=new ArrayList<>();
do{
cnt++;
for(Integer x:rem){
removed[x.intValue()]=true;
for(i=1;i<=n;i++){
if(!removed[i]){
g[i].remove(x);
}
}
}
rem.clear();
for(i=1;i<=n;i++){
if(!removed[i] && g[i].size()==1){
rem.add(i);
}
}
}while(!rem.isEmpty());
sop(cnt);
/*
.
.
.
.
.
.
.
*/
}
/*
temporary functions
.
.
*/
/*
fuctions
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
abcdefghijklmnopqrstuvwxyz
.
.
.
.
.
.
*/
static int modulo(int j,int m){
if(j<0)
return m+j;
if(j>=m)
return j-m;
return j;
}
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static final boolean debug=true;
static Reader in=new Reader();
static StringBuilder ans=new StringBuilder();
static long powm(long a,long b,long m){
long an=1;
long c=a;
while(b>0){
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static Random rn=new Random();
static void sop(Object a){System.out.println(a);}
static int ni(){return in.nextInt();}
static int[] nia(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=ni();return a;}
static long nl(){return in.nextLong();}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String ns(){return in.next();}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double nd(){return in.nextDouble();}
static double[] nda(int n){double a[]=new double[n];for(int i=0;i<n;i++)a[i]=nd();return a;}
static class Reader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader(){
reader=new BufferedReader(new InputStreamReader(System.in),32768);
tokenizer=null;
}
public String next(){
while(tokenizer==null || !tokenizer.hasMoreTokens()){
try{
tokenizer=new StringTokenizer(reader.readLine());
}
catch(IOException e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | dc23cc8c238ca30d3f5b1bbdb797f29a | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 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.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.math.BigInteger;
import javax.swing.text.StyledEditorKit.ForegroundAction;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt() ;
int m = in.nextInt() ;
int h [] = new int[101] ;
boolean ischanged [] = new boolean [101] ;
int a [] = new int [m] ;
int b [] = new int [m] ;
for (int i = 0; i < m; i++) {
a[i] = in.nextInt() ;
b[i] = in.nextInt() ;
h[a[i]] ++ ;
h[b[i]] ++ ;
}
int g= 0 ;
boolean val = false ;
for (int k = 0; k < h.length; k++){
for (int i = 0; i < h.length; i++)
if(h[i]==1 && !ischanged[i])
{
val = true ;
h[i]=0 ;
for (int j = 0; j < a.length; j++)
if(i==a[j] && h[b[j]]!=0){
h[b[j]] -- ;
ischanged[b[j]]=true;
break ;
}
else if (i==b[j] && h[a[j]]!=0){
h[a[j]] -- ;
ischanged[a[j]]=true ;
break ; }
}
if(val){
g++ ;
val = false ;
for (int i = 0; i < ischanged.length; i++) {
ischanged[i] = false ;
}
}
else
break ;
}
out.println(g);
}
}
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 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 1b52b58dd10f0b329f6dfa04c3bd7a72 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | //package main;
import java.awt.Point;
import java.io.*;
import java.util.*;
public final class Main {
BufferedReader br;
StringTokenizer stk;
public static void main(String[] args) throws Exception {
new Main().run();
}
{
stk = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
long mod = 1000_000_000 + 7;
void run() throws Exception {
int n = ni(), m = ni();
HashSet<Integer>[] graph = new HashSet[n + 1];
for(int i=1; i<=n; i++)
graph[i] = new HashSet<>();
for(int i=0; i<m; i++) {
int a = ni(), b = ni();
graph[a].add(b);
graph[b].add(a);
}
int kicked = 0;
while(found(graph)) {
kicked++;
HashSet<Integer> remove = new HashSet<>();
for(int i=1; i<=n; i++) {
if(graph[i] == null)
continue;
if(graph[i].size() == 1) {
remove.add(i);
}
}
for(int node : remove) {
for(int adj : graph[node]) {
graph[node].remove(adj);
graph[adj].remove(node);
}
}
}
System.out.println(kicked);
}
boolean found(HashSet<Integer>[] g) {
for(int i=1; i<g.length; i++) {
if(g[i] == null)
continue;
if(g[i].size() == 1) {
return true;
}
}
return false;
}
//Reader & Writer
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(br.readLine(), " ");
}
return stk.nextToken();
}
String nt() throws Exception {
return nextToken();
}
int ni() throws Exception {
return Integer.parseInt(nextToken());
}
long nl() throws Exception {
return Long.parseLong(nextToken());
}
double nd() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 6e82e8e97e751dfc523d3fda118b3bd4 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in =new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int from[] = new int[m];
int to[] = new int[m];
boolean deleteedge[] = new boolean[m];
int count[] = new int[n+1];
for(int i=0;i<m;i++){
from[i] = in.nextInt();
to[i] = in.nextInt();
count[from[i]]++;
count[to[i]]++;
}
int ans = 0;
boolean b[] = new boolean[n+1];
while(true){
int c = 0;
for(int i=1;i<=n;i++){
if(count[i]==1){
c++;
b[i] = true;
}
}
if(c==0){
break;
}
for(int i=0;i<m;i++){
if(!deleteedge[i]){
if(b[from[i]]||b[to[i]]){
deleteedge[i] = true;
count[from[i]]--;
count[to[i]]--;
}
}
}
ans++;
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 91b492b6154389ec4490d5fbf5c0cac7 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class StudentsAndShoeLaces
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt(), ans = 0, m = in.nextInt(), a[][] = new int [n][n], st[] = new int[n];
for (int i = 0; i < m; i++) {
int x = in.nextInt(), y = in.nextInt();
a[x - 1][y - 1] = 1;
a[y - 1][x - 1] = 1;
}
boolean ok = true;
while (ok) {
ok = false; int size = 0;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < n; j++) sum += a[i][j];
if (sum == 1) { st[size++] = i; ok = true; }
}
if (ok) ans++;
for (int i = 0; i < size; i++)
for (int j = 0; j < n; j++) {
a[st[i]][j] = 0;
a[j][st[i]] = 0;
}
}
System.out.println(ans);
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 3c91ba272825167af9a09dc0657f654a | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class StudentsAndShoelaces {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer s = new StringTokenizer(in.readLine());
int n = Integer.parseInt(s.nextToken());
int m = Integer.parseInt(s.nextToken());
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
int[] deg = new int[n];
for (int i = 0; i < m; i++) {
s = new StringTokenizer(in.readLine());
int a = Integer.parseInt(s.nextToken()) - 1;
int b = Integer.parseInt(s.nextToken()) - 1;
adj[a].add(b);
adj[b].add(a);
deg[a]++;
deg[b]++;
}
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
if(deg[i] == 1)q.add(i);
}
Queue<Integer> qn = new LinkedList<Integer>();
int res = 0;
boolean first = true;
while(true) {
while(!q.isEmpty()) {
// System.out.println(q);
// System.out.println(qn);
int cur = q.poll();
if(deg[cur] == 1){
if(first) { res++; first = false; }
for (int d : adj[cur]) {
deg[d]--;
if(deg[d] == 1)
qn.add(d);
}
}
}
if(q.isEmpty() && qn.isEmpty()) break;
q = qn;
qn = new LinkedList<>();
first = true;
}
System.out.println(res);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | c91c78329ce9bae9846293a6d4602a18 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
private static FastReader fr = new FastReader();
private static Helper hp = new Helper();
private static StringBuilder result = new StringBuilder();
public static void main(String[] args) {
Task solver = new Task();
solver.solve();
}
static class Task {
class Graph {
public HashMap<Integer, HashSet<Integer>> map;
public Graph(){
map = new HashMap<>();
}
public void addEdge(int src, int dest) {
if(!map.containsKey(src)) map.put(src, new HashSet<>());
if(!map.containsKey(dest)) map.put(dest, new HashSet<>());
map.get(src).add(dest);
map.get(dest).add(src);
}
}
public void solve() {
int n = fr.ni();
int[] arr = new int[n+1];
Graph graph = new Graph();
int con = fr.ni();
for(int i=0; i<con; i++){
int s1 = fr.ni(), s2 = fr.ni();
graph.addEdge(s1, s2);
}
HashMap<Integer, HashSet<Integer>> map = graph.map;
int count = 0;
while(true){
boolean onePresent = false;
HashMap<Integer, ArrayList<Integer>> removeItems = new HashMap<>();
for(Map.Entry<Integer, HashSet<Integer>> entry : map.entrySet()){
if(entry.getValue().size() == 1){
onePresent = true;
int val = entry.getValue().iterator().next();
entry.getValue().remove(val);
ArrayList<Integer> sub = removeItems.getOrDefault(val, new ArrayList<>());
sub.add(entry.getKey());
removeItems.put(val, sub);
}
}
for(Map.Entry<Integer, ArrayList<Integer>> entry : removeItems.entrySet()){
if(map.containsKey(entry.getKey())){
for(int i : entry.getValue()){
map.get(entry.getKey()).remove(i);
if(map.get(entry.getKey()).isEmpty()) map.remove(i);
}
}
}
if(!onePresent) break;
count++;
}
System.out.println(count);
}
}
static class Helper {
public int[] ipArrInt(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fr.ni();
return arr;
}
public long[] ipArrLong(int n, int si) {
long[] arr = new long[n];
for (int i = si; i < n; i++)
arr[i] = fr.nl();
return arr;
}
}
static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
private static PrintWriter pw;
public FastReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public String rl() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = fr.ni();
return arr;
}
public void print(String str) {
pw.print(str);
pw.flush();
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 5b2c5a6dc38e0af186951ef7cdfe9d5d | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
HashMap<Integer, ArrayList<Integer>> A = new HashMap<>();
for (int i=0; i<m; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
if (A.get(x) != null) {
ArrayList temp = A.get(x);
temp.add(y);
} else {
ArrayList tempArray = new ArrayList<>();
tempArray.add(y);
A.put(x, tempArray);
}
if (A.get(y) != null) {
ArrayList temp = A.get(y);
temp.add(x);
} else {
ArrayList tempArray = new ArrayList<>();
tempArray.add(x);
A.put(y, tempArray);
}
}
int ans = 0;
while (true) {
final boolean[] flag = {false};
Map<Integer, Integer> temp = new HashMap<>();
A.forEach((key,integerList)-> {
if (integerList.size() == 1) {
int x = integerList.get(0);
temp.put(key, x);
flag[0] = true;
}
});
temp.forEach((key,key2)-> {
if (A.get(key).size() == 1) A.get(key).remove(0);
if (A.get(key2).size() > 0) A.get(key2).remove(key);
});
if (! flag[0]) {
break;
} else {
ans += 1;
}
}
System.out.println(ans);
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | b20e391bc9564ba8e557cb4c8d534d98 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class TaskB {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] adjMat = new int[n][n];
for (int i = 0 ; i < m ; i++){
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjMat[u][v] = 1;
adjMat[v][u] = 1;
}
boolean f = true;
int ans = 0;
while (f) {
f = false;
Queue<Integer> qu = new LinkedList<>();
for (int i = 0; i < n; i++) {
int neighbor = 0;
int idx = 0;
for (int j = 0; j < n; j++) {
neighbor += adjMat[i][j];
if(adjMat[i][j] == 1)
idx = j;
}
if(neighbor == 1)
{
qu.add(i);
qu.add(idx);
f = true;
}
}
while (!qu.isEmpty()){
int u = qu.poll();
int v = qu.poll();
adjMat[u][v]= 0;
adjMat[v][u]= 0;
}
if(f) ans++;
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | b74fab4ff8265b9bee23fe77090e6604 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.sql.Array;
import java.util.*;
public class TaskC {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
ArrayList[] arr = new ArrayList[n];
for (int i = 0 ; i < n ; i++)
arr[i] = new ArrayList();
int m = sc.nextInt();
while (m-->0)
{
int u = sc.nextInt() -1;
int v = sc.nextInt() - 1;
arr[u].add(v);
arr[v].add(u);
}
int ans= 0;
while(true)
{
boolean f = false;
ArrayList<Integer> al = new ArrayList<>();
for (Integer i = 0 ; i<n ;i++)
{
if(arr[i].size() == 1)
{
al.add(i);
}
}
if(al.isEmpty())
break;
ans++;
// System.out.println(Arrays.toString(arr));
for (Integer i = 0 ; i<al.size() ; i++)
{
int u = al.get(i);
// System.out.println(arr[u] + " "+u);
if(!arr[u].isEmpty()) {
arr[(int) arr[u].get(0)].remove(arr[(int) arr[u].get(0)].indexOf(u));
arr[u].remove(0);
}
}
}
pw.print(ans);
pw.close();
}
private static int gcd(int a, int b) {
if( b == 0)
return a;
return gcd(b , a%b);
}
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 o) {
if(x == o.x)
return y - o.y;
return x - o.x;
}
public double dis(Pair a){
return (a.x - x)*(a.x - x) + (a.y-y)*(a.y-y);
}
public String toString() {
return x + " " + y;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public boolean check() {
if (!st.hasMoreTokens())
return false;
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
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() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | da10542d6ee0696ae25aa3c4712bba0e | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 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.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class TaskB {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<Integer>();
for (int i = 0; i < m; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
int c = 0;
while (true) {
HashSet<Integer> set = new HashSet<Integer>();
boolean f = false;
boolean ones = true;
for (int i = 0; i < n; i++) {
if (adj[i].size() == 1) {
set.add(i);
f = true;
}
if (adj[i].size() > 1)
ones = false;
}
for (int i = 0; i < n; i++) {
if(set.contains(i))
adj[i].remove(0);
for (int j = 0; j < adj[i].size(); j++) {
if (set.contains(adj[i].get(j))) {
adj[i].remove(j);
j--;
}
}
}
if (!f)
break;
c++;
}
System.out.println(c);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 452272227b5fa8ade77cd6b176966f40 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.util.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static final double EPS = 1e-9;
static long mod = 998244353;
static int inf = (int) 1e9 + 2;
static long[] fac;
static int[] si;
static ArrayList<Integer> primes;
static TreeSet<Integer>[] ad;
static ArrayList<pair>[] d;
static edge[] ed;
static boolean f;
static int n, m;
static int[][] a;
static Queue<Integer>[] can;
static String[] ss;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
ad=new TreeSet[n];
for(int i=0;i<n;i++)
ad[i]=new TreeSet();
for(int i=0;i<m;i++) {
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
ad[a].add(b);
ad[b].add(a);
}
int ans=0;
for(int i=0;i<n;i++) {
boolean []b=new boolean [n];
int v=0;
for(int j=0;j<n;j++) {
if(ad[j].size()==1) {
v++;
b[j]=true;
}
}
if(v==0)
break;
for(int u=0;u<n;u++) {
if(b[u] && ad[u].size()==1) {
// System.out.println(u+" "+ad[u]);
ad[ad[u].first()].remove(u);
ad[u]=new TreeSet<>();
}
}
ans++;
}
out.print(ans);
out.close();
}
static Queue<Integer> k, k1;
static boolean hg = false;
static class Edge implements Comparable<Edge>
{
int node, cost;
Edge(int a, int b) { node = a; cost = b; }
public int compareTo(Edge e){ return cost - e.cost; }
}
static void ifCan(int i) {
if (i == 6) {
hg = true;
for (int j : k)
k1.add(j);
return;
} else if (k.contains(i))
ifCan(i + 1);
else {
if (!hg) {
for (int p : can[i]) {
if (!k.contains(p)) {
k.add(i);
k.add(p);
ifCan(i + 1);
k.remove(i);
k.remove(p);
}
}
}
}
}
static class qu implements Comparable<qu> {
int a;
int b;
qu(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return a + " " + b;
}
@Override
public int compareTo(qu o) {
return b - o.b;
}
}
static class pair {
int to;
int number;
pair(int t, int n) {
number = n;
to = t;
}
public String toString() {
return to + " " + number;
}
}
static void con() {
for (int i = 0; i < n; i++)
d[i] = new ArrayList();
for (int i = 0; i < m; i++) {
if (in[i]) {
edge w = ed[i];
d[w.from].add(new pair(w.to, w.number));
d[w.to].add(new pair(w.from, w.number));
}
}
}
static boolean[] in;
/*
* static void mst() { Arrays.sort(ed); UnionFind uf=new UnionFind(n); for(int
* i=0;i<m;i++) { edge w=ed[i]; if(!uf.union(w.from, w.to)) continue;
* in[i]=true; } }
*/
static class edge implements Comparable<edge> {
int from;
int to;
int number;
edge(int f, int t, int n) {
from = f;
to = t;
number = n;
}
public String toString() {
return from + " " + to + " " + number;
}
public int compareTo(edge f) {
return number - f.number;
}
}
static class seg implements Comparable<seg> {
int a;
int b;
seg(int s, int e) {
a = s;
b = e;
}
public String toString() {
return a + " " + b;
}
public int compareTo(seg o) {
// if(a==o.a)
return o.b - b;
// return
}
}
static long power(int i) {
// if(i==0)
// return 1;
long a = 1;
for (int k = 0; k < i; k++)
a *= i;
return a;
}
static void seive() {
si = new int[1000001];
primes = new ArrayList<>();
int N = 1000001;
si[1] = 1;
for (int i = 2; i < N; i++) {
if (si[i] == 0) {
si[i] = i;
primes.add(i);
}
for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++)
si[primes.get(j) * i] = primes.get(j);
}
}
static long inver(long x) {
int a = (int) x;
long e = (mod - 2);
long res = 1;
while (e > 0) {
if ((e & 1) == 1) {
// System.out.println(res*a);
res = (int) ((1l * res * a) % mod);
}
a = (int) ((1l * a * a) % mod);
e >>= 1;
}
// out.println(res+" "+x);
return res % mod;
}
static public class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
int[] array, sTree, lazy;
SegmentTree(int[] in)
{
array = in; N = in.length - 1;
sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new int[N<<1];
build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e)
sTree[node] = array[b];
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = sTree[node<<1]+sTree[node<<1|1];
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] += val;
while(index>1)
{
index >>= 1;
sTree[index] = sTree[index<<1] + sTree[index<<1|1];
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j, int val)
{
if(i > e || j < b)
return;
if(b >= i && e <= j)
{
sTree[node] += (e-b+1)*val;
lazy[node] += val;
}
else
{
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = sTree[node<<1] + sTree[node<<1|1];
}
}
void propagate(int node, int b, int mid, int e)
{
lazy[node<<1] += lazy[node];
lazy[node<<1|1] += lazy[node];
sTree[node<<1] += (mid-b+1)*lazy[node];
sTree[node<<1|1] += (e-mid)*lazy[node];
lazy[node] = 0;
}
int query(int i, int j)
{
return query(1,1,N,i,j);
}
int query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return 0;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
int q1 = query(node<<1,b,mid,i,j);
int q2 = query(node<<1|1,mid+1,e,i,j);
return q1 + q2;
}
}
static long fac(int n) {
if (n == 0)
return fac[n] = 1;
if (n == 1)
return fac[n] = 1;
long ans = 1;
for (int i = 1; i <= n; i++)
fac[i] = ans = (i % mod * ans % mod) % mod;
return ans % mod;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class unionfind {
int[] p;
int[] size;
unionfind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
Arrays.fill(size, 1);
}
int findSet(int v) {
if (v == p[v])
return v;
return p[v] = findSet(p[v]);
}
boolean sameSet(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a == b)
return true;
return false;
}
int max() {
int max = 0;
for (int i = 0; i < size.length; i++)
if (size[i] > max)
max = size[i];
return max;
}
boolean combine(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a == b)
return true;
if (size[a] > size[b]) {
p[b] = a;
size[a] += size[b];
} else {
p[a] = b;
size[b] += size[a];
}
return false;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 169b34f59bdac8128f1d4e6f428ad195 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
public class CF_Shoelaces {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
Student[] students = new Student[n];
for (int i=0; i<n; i++){
students[i] = new Student();
}
for (int i=0; i<m; i++){
st = new StringTokenizer(br.readLine());
int s1 = Integer.parseInt(st.nextToken())-1;
int s2 = Integer.parseInt(st.nextToken())-1;
students[s1].tied.add(s2);
students[s2].tied.add(s1);
}
Queue<Integer> ones = new LinkedList<Integer>();
for (int i=0; i<n; i++){
if (students[i].tied.size()==1){
ones.add(i);
students[i].lvl = 1;
}
}
int mxL = 0;
while (!ones.isEmpty()){
//bfs down each one
int rem = ones.poll();
if (students[rem].tied.size()==0){
continue;
}
mxL = Math.max(mxL, students[rem].lvl);
Student to = students[students[rem].tied.get(0)];//going to next student
to.tied.removeIf(student -> student==rem);//remove from
if (to.tied.size()==1){
ones.offer(students[rem].tied.get(0));
to.lvl = students[rem].lvl+1;
}
}
System.out.println(mxL);
}
public static class Student{
public ArrayList<Integer> tied;
public int lvl;
public Student(){
tied = new ArrayList<Integer>();
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | e98ed2b99d5e776f0ad83d90c33259a0 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class r129b {
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r129b1 ob=new r129b1(n);
for(int i=0;i<m;i++)
{
int u=in.nextInt();
int v=in.nextInt();
ob.setEdge(u, v);
ob.setEdge(v, u);
}
ob.solve();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt(){
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r129b1 {
private TreeMap<Integer,LinkedList<Integer>> adj;
public r129b1(int v)
{
adj=new TreeMap<Integer,LinkedList<Integer>>();
for(int i=0;i<v;i++)
{
adj.put(i+1,new LinkedList<Integer>());
}
}
public void setEdge(int a,int b)
{
adj.get(a).add(b);
}
public LinkedList<Integer> getEdge(int a)
{
return adj.get(a);
}
public boolean contain(int a, int b)
{
return adj.get(a).contains(b);
}
public int numofEdges(int a)
{
return adj.get(a).size();
}
public void removeEdge(int a,int b)
{
int pos=adj.get(a).indexOf(b);
adj.get(a).remove(pos);
//System.out.println("adj is now"+adj);
}
public void removeVertex(int a)
{
adj.get(a).clear();
}
void solve()
{
int flag=0,count=0;
TreeSet<Integer> ts=new TreeSet<Integer>();
while(flag==0)
{
flag=-1;
for(int i=0;i<adj.size();i++)
{
//System.out.println("size of"+(i+1)+" is"+adj.get(i+1).size());
if(!ts.contains(i+1)&&adj.get(i+1).size()==1)
{
flag=0;
int u=i+1;
int v=adj.get(i+1).get(0);
removeEdge(u,v);
removeEdge(v,u);
ts.add(v);
//System.out.println("adj is now"+adj);
}
}
ts.clear();
count++;
}
System.out.println(count-1);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | a5567f8e7430902240d262a161f6cb2c | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class r129b {
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r129b1 ob=new r129b1(n);
for(int i=0;i<m;i++)
{
int u=in.nextInt();
int v=in.nextInt();
ob.setEdge(u, v);
ob.setEdge(v, u);
}
ob.solve();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r129b1 {
private TreeMap<Integer,LinkedList<Integer>> adj;
public r129b1(int v)
{
adj=new TreeMap<Integer,LinkedList<Integer>>();
for(int i=0;i<v;i++)
{
adj.put(i+1,new LinkedList<Integer>());
}
}
public void setEdge(int a,int b)
{
adj.get(a).add(b);
}
public LinkedList<Integer> getEdge(int a)
{
return adj.get(a);
}
public boolean contain(int a, int b)
{
return adj.get(a).contains(b);
}
public int numofEdges(int a)
{
return adj.get(a).size();
}
public void removeEdge(int a,int b)
{
int pos=adj.get(a).indexOf(b);
adj.get(a).remove(pos);
//System.out.println("adj is now"+adj);
}
public void removeVertex(int a)
{
adj.get(a).clear();
}
void solve()
{
int flag=0,count=0;
TreeSet<Integer> ts=new TreeSet<Integer>();
while(flag==0)
{
flag=-1;
for(int i=0;i<adj.size();i++)
{
//System.out.println("size of"+(i+1)+" is"+adj.get(i+1).size());
if(!ts.contains(i+1)&&adj.get(i+1).size()==1)
{
flag=0;
int u=i+1;
int v=adj.get(i+1).get(0);
removeEdge(u,v);
removeEdge(v,u);
ts.add(v);
//System.out.println("adj is now"+adj);
}
}
ts.clear();
count++;
}
System.out.println(count-1);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | a5b76258c3a0ef0bd113fe74fbe96562 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import javax.print.DocFlavor;
import java.io.*;
import java.math.BigInteger;
import java.nio.Buffer;
import java.sql.BatchUpdateException;
import java.util.*;
import java.util.stream.Stream;
import java.util.Vector;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static java.lang.Math.*;
import java.util.*;
import java.nio.file.StandardOpenOption;
public class icpc
{
public static void main(String[] args)throws IOException
{
Reader in = new Reader();
int n = in.nextInt();
int k = in.nextInt();
ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++)
adj[i] = new ArrayList<>();
for(int i=0;i<k;i++)
{
int a = in.nextInt();
int b = in.nextInt();
adj[a-1].add(b-1);
adj[b-1].add(a-1);
}
int count = 0;
while(true)
{
ArrayList<Integer> indices = new ArrayList<>();
for(int i=0;i<n;i++)
if(adj[i].size() == 1)
indices.add(i);
if(indices.size() == 0)
break;
else
count++;
for(int i=0;i<indices.size();i++)
{
for(int j=0;j<n;j++)
{
if(adj[j].contains(indices.get(i)))
adj[j].remove(Integer.valueOf(indices.get(i)));
}
}
for(int i=0;i<indices.size();i++)
adj[indices.get(i)].clear();
}
System.out.println(count);
}
}
class Solver
{
public void solve(long[] A,Game[] B)
{
}
}
class Point implements Comparable<Point>
{
int x;
int y;
Point(int a ,int b)
{
this.x = a;
this.y = b;
}
public int compareTo(Point ob)
{
if(ob.x < this.x)
return 1;
else if(ob.x > this.x)
return -1;
else
return 0;
}
}
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class Node
{
int[] A;
int moves;
Node(int[] B,int c)
{
this.A = new int[B.length];
A = B.clone();
this.moves = c;
}
@Override
public boolean equals(Object ob)
{
if(ob == null)
return false;
if(!(ob instanceof Node))
return false;
if(ob == this)
return true;
Node obj = (Node)ob;
boolean flag = true;
for(int i=0;i<obj.A.length;i++)
{
if(this.A[i] != obj.A[i])
flag = false;
}
return (flag & (obj.moves == this.moves));
}
@Override
public int hashCode()
{
return (int)this.A.length;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class Game
{
int last;
int diff;
boolean flag;
Game(int a,int b,boolean z)
{
this.last = a;
this.diff = b;
this.flag = z;
}
}
class Play implements Comparable<Play>
{
int x;
int y;
Play(int a,int b)
{
this.x = a;
this.y = b;
}
@Override
public int compareTo(Play ob)
{
if(this.x > ob.x)
return -1;
else if(this.x < ob.x)
return 1;
else
{
if(this.y < ob.y)
return -1;
else
return 1;
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 34a8c717b17d231d7232c01d437ea4a2 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class StudentsAndShoelaces implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni(), m = in.ni();
List<Integer>[] graph = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int u = in.ni(), v = in.ni();
graph[u].add(v);
graph[v].add(u);
}
List<Integer> queue = new ArrayList<>();
int result = -1;
boolean[] removed = new boolean[n + 1];
do {
result++;
for (Integer x : queue) {
removed[x] = true;
for (int i = 1; i <= n; i++) {
if (!removed[i])
graph[i].remove(x);
}
}
queue.clear();
for (int i = 1; i <= n; i++) {
if (!removed[i] && graph[i].size() == 1) {
queue.add(i);
}
}
} while (!queue.isEmpty());
out.println(result);
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (StudentsAndShoelaces instance = new StudentsAndShoelaces()) {
instance.solve();
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 05dfd8305dc6d216feaccd30ecae9eb2 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args){
FastScanner scanner = new FastScanner();
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] a = new int[m];
int[] b = new int[m];
for(int i = 0; i < m; i++){
a[i] = scanner.nextInt()-1;
b[i] = scanner.nextInt()-1;
}
boolean[] used = new boolean[m];
int ans = 0;
int tmp = 0;
for(int i = 0; i < n; i++){
int[] cnt = new int[n];
for(int j = 0; j < n; j++){
cnt[i] = 0;
}
for(int j = 0; j < m; j++){
if(!used[j]){
cnt[a[j]]++;
cnt[b[j]]++;
}
}
int num = 0;
for(int j = 0; j < m; j++){
if(!used[j] && (cnt[a[j]] == 1 || cnt[b[j]] == 1)){
used[j] = true;
}
if(used[j]){
num++;
}
}
if(tmp < num){
tmp = num;
ans++;
}
}
System.out.println(ans);
}
private static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b)){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() { return Double.parseDouble(next());}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | de840049030f9601733879d7d4c354fb | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes |
/*
*
* Date: 07 September 2019
* Time: 01:03:00
*/
import java.io.*;
import java.util.*;
public class sh
{
public static void main(String[] args) throws NumberFormatException, IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int dd[]=new int[n];
boolean arr[][]=new boolean[n][n];
for(int i=0;i<m;i++){
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
arr[x][y]=true;
arr[y][x]=true;
dd[x]++;
dd[y]++;
}
int cnt=0;
int g=0;
while(1==1){
cnt=0;
for(int i=0;i<n;i++){
if(dd[i]==1){
cnt++;
dd[i]=-1;
}
}
if(cnt==0){
break;
}
g++;
for(int i=0;i<n;i++){
if(dd[i]==-1){
for(int j=0;j<n;j++){
if(arr[i][j]){
arr[i][j]=false;
arr[j][i]=false;
dd[i]=0;
dd[j]--;
break;
}
}
}
}
}
System.out.println(g);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | b8b5db9b1e62d5f8946e6e910fe75d2a | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int a, b;
int[][] nodes = new int[n][n];
for (int i = 0; i < m; i++) {
a = scanner.nextInt();
b = scanner.nextInt();
nodes[a - 1][b - 1] = 1;
nodes[b - 1][a - 1] = 1;
}
int cnt = 0;
boolean recheck = true;
int[] misbehave = new int[n];
while (recheck) {
recheck = false;
int size = 0;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < n; j++)
sum += nodes[i][j];
if (sum == 1) {
misbehave[size] = i;
size++;
recheck = true;
}
}
if (recheck)
cnt++;
// removal
for (int i = 0; i < size; i++) {
for (int j = 0; j < n; j++) {
nodes[misbehave[i]][j] = 0;
nodes[j][misbehave[i]] = 0;
}
}
}
System.out.println(cnt);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 971c25a81462e5931122e949998168c2 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class fourteen {
public static void main(String[] args) {
Scanner scn= new Scanner(System.in);
int n= scn.nextInt();
int m= scn.nextInt();
Map<Integer,List<Integer>> mymap = new HashMap<Integer,List<Integer>>();
Map<Integer,List<Integer>> cpmap = new HashMap<Integer,List<Integer>>();
List<Integer> rmlist= new ArrayList<Integer>();
List<Integer> rvlist= new ArrayList<Integer>();
// Map<Integer,List<Integer>> rmmap = new HashMap<Integer,List<Integer>>();
int i=0;
List<Integer> temp;
int t1;
int t2;
while(i<m)
{
t1= scn.nextInt();
t2= scn.nextInt();
if(mymap.containsKey(t1))
{
temp= mymap.get(t1);
temp.add(t2);
mymap.put(t1,temp);
}
else
{
temp= new ArrayList<Integer>();
temp.add(t2);
mymap.put(t1,temp);
}
if(mymap.containsKey(t2))
{
temp= mymap.get(t2);
temp.add(t1);
mymap.put(t2,temp);
}
else
{
temp= new ArrayList<Integer>();
temp.add(t1);
mymap.put(t2,temp);
}
i++;
}
// System.out.println(mymap);
boolean itrcount=true;
int itr=0;
int count=0;
while(mymap.size()>=0)
{
rmlist.clear();
rvlist.clear();
itr++;
Set<Map.Entry<Integer,List<Integer>>> tr=mymap.entrySet();
count=0;
for(Map.Entry<Integer,List<Integer>> tre:tr)
{
temp=tre.getValue();
if(temp.size()==1)
{
rmlist.add(tre.getKey());
rvlist.add(tre.getValue().get(0));
count++;
}
}
if(count==0)
{
break;
}
i=0;
for(Integer t:rmlist)
{
if(mymap.containsKey(rvlist.get(i)))
{
temp=mymap.get(rvlist.get(i));
if(temp.contains(t))
temp.remove(t);
// System.out.println(temp);
if(mymap.containsKey(t))
mymap.remove(t);
}
i++;
}
// System.out.println(mymap);
// System.out.println(itr);
}
System.out.println(--itr);
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 365ec56cac5ced4d8c047a5981852437 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by Tejas on 01-07-2018.
*/
public class Main {
static HashSet<Integer>[] adjList;
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String temp[]=bufferedReader.readLine().split(" ");
int N=Integer.parseInt(temp[0]);
int M=Integer.parseInt(temp[1]);
adjList=new HashSet[N+1];
for(int i=0;i<=N;i++)
adjList[i]=new HashSet();
for(int i=0;i<M;i++) {
temp=bufferedReader.readLine().split(" ");
int x=Integer.parseInt(temp[0]);
int y=Integer.parseInt(temp[1]);
adjList[x].add(y);
adjList[y].add(x);
}
System.out.println(solve(N));
}
private static int solve(int N) {
boolean atleastOneDeleted=true;
int groups=0;
while(atleastOneDeleted){
HashSet<Integer> hashSet=new HashSet<>();
atleastOneDeleted=false;
boolean addGroups=false;
for(int i=1;i<=N;i++)
if(adjList[i].size()==1 && !hashSet.contains(i)){
for(int j: adjList[i]){
hashSet.add(j);
adjList[i].remove(j);
adjList[j].remove(i);
// addGroups=true;
}
atleastOneDeleted=true;
}
if(atleastOneDeleted) groups++;
}
return groups;
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 8467f632c21f99564356cc15cd9bcb95 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by Tejas on 01-07-2018.
*/
public class Main {
static HashSet<Integer>[] adjList;
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String temp[]=bufferedReader.readLine().split(" ");
int N=Integer.parseInt(temp[0]);
int M=Integer.parseInt(temp[1]);
adjList=new HashSet[N+1];
for(int i=0;i<=N;i++)
adjList[i]=new HashSet();
for(int i=0;i<M;i++) {
temp=bufferedReader.readLine().split(" ");
int x=Integer.parseInt(temp[0]);
int y=Integer.parseInt(temp[1]);
adjList[x].add(y);
adjList[y].add(x);
}
System.out.println(solve(N));
}
private static int solve(int N) {
boolean atleastOneDeleted=true;
int groups=0;
while(atleastOneDeleted){
HashSet<Integer> hashSet=new HashSet<>();
atleastOneDeleted=false;
boolean addGroups=false;
for(int i=1;i<=N;i++)
if(adjList[i].size()==1 && !hashSet.contains(i)){
for(int j: adjList[i]){
hashSet.add(j);
adjList[i].remove(j);
adjList[j].remove(i);
addGroups=true;
}
atleastOneDeleted=true;
}
if(addGroups) groups++;
}
return groups;
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 1b0a6ec8e76a7cdb355f45619565e2af | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
//267630EY
public class Main129B2
{
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Vector<Integer>[] graph=(Vector<Integer>[]) new Vector[n];
for(int i=0;i<n;i++)
graph[i]=new Vector<Integer>();
for(int i=0;i<m;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
x--;
y--;
graph[x].add(y);
graph[y].add(x);
}
int ans=0;
while(true)
{
boolean pos=false;
Vector<Integer> del=new Vector<Integer>();
for(int i=0;i<n;i++)
{
if(graph[i].size()==1)
{
del.add(i);
del.add(graph[i].elementAt(0));
pos=true;
}
}
if(!pos) break;
ans++;
for(int i=0;i<del.size();i++)
{
int x=del.elementAt(i);
int y=del.elementAt(i+1);
graph[x].removeElement(y);
graph[y].removeElement(x);
i+=1;
}
}
out.println(ans);
out.flush();
}
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 56244fefc29011b77cafe508effae263 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main129B
{
static class Graph
{
Vector<Integer>[] G;
public Graph(int n)
{
G=(Vector<Integer>[]) new Vector[n];
for(int i=0;i<n;i++)
G[i]=new Vector<Integer>();
}
public void add(int v,int w)
{
G[v].add(w);
G[w].add(v);
}
public Iterable<Integer> adj(int v)
{
return G[v];
}
}
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Graph g=new Graph(n);
for(int i=0;i<m;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
x--;
y--;
g.add(x,y);
}
boolean marked[]=new boolean[n];
int ans=0;
while(true)
{
boolean flag=false;
int k=0;
//int[][] w=new int[n][n];
int[] w=new int[n];
int[] v=new int[n];
for(int i=0;i<n;i++)
{
if(!marked[i])
{
for(int j:g.adj(i))
{
if(g.G[j].size()==1&&!marked[j])
{
flag=true;
marked[j]=true;
w[k]=j;
v[k++]=i;
}
}
}
}
if(!flag) break;
for(int i=0;i<k;i++)
{
g.G[w[i]].remove((Integer)v[i]);
g.G[v[i]].remove((Integer)w[i]);
}
ans++;
}
out.println(ans);
out.flush();
}
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 9e74edfd442b4edeb834d7dbf566a0e4 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int count = 0;
LinkedList<Integer>[] graph = new LinkedList[n];
for(int i=0; i<n; i++)
graph[i] = new LinkedList<Integer>();
// taking input
for(int i=0; i<m; i++) {
int x = input.nextInt()-1;
int y = input.nextInt()-1;
graph[x].add(y);
graph[y].add(x);
}
//solving
while(true) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<n; i++) {
if(graph[i].size() == 1)
list.add(i);
}
int size = list.size();
if(size > 0) {
count++;
for(int i=0; i<size; i++) {
int num = list.get(i);
if( ! graph[num].isEmpty()) {
int secondNum = graph[num].get(0);
graph[num].clear();
graph[secondNum].remove((Integer)num);
}
}
}else {
break;
}
}
System.out.println(count);
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | fb4ea7daf93fe6a9b5cac312143891f1 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class B129 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int M = in.nextInt();
Node[] nodes = new Node[N];
for (int n=0; n<N; n++) {
nodes[n] = new Node();
}
for (int m=0; m<M; m++) {
int u = in.nextInt()-1;
int v = in.nextInt()-1;
Node nodeu = nodes[u];
Node nodev = nodes[v];
nodeu.next.add(nodev);
nodev.next.add(nodeu);
}
int answer = 0;
while (true) {
List<Node> list = new ArrayList<>();
for (Node node : nodes) {
if (node.next.size() == 1) {
list.add(node);
}
}
if (list.isEmpty()) {
break;
}
for (Node rep : list) {
for (Node node : rep.next) {
node.next.remove(rep);
}
rep.next.clear();
}
answer++;
}
System.out.println(answer);
}
static class Node {
Set<Node> next = new HashSet<>();
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 5fb68d25540b85fafdec123ba98b5688 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
static Node[] node;
static int vis[],nb[];
static int bfs(int start,int n){
for(int i=1;i<=n;i++){
if(vis[i]==-1) continue;
vis[i]=0;
}
int sid=0;
vis[start]=1;
ArrayDeque<Integer> q=new ArrayDeque<>();
q.add(start);
while(q.size()!=0){
int curr=q.poll();
for(int ele:node[curr].adj){
if(vis[ele]==0){
sid++;
vis[ele]=1;
}
}
}
return sid;
}
public static void main(String[] args) {
FastScanner sc =new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
node =new Node[n+1];
vis=new int[n+1];
nb=new int[n+1];
for(int i=0;i<n+1;i++) node[i]=new Node();
for(int i=0;i<m;i++)
{
int u=sc.nextInt(),v=sc.nextInt();
node[u].adj.add(v);
node[v].adj.add(u);
}
int res=0;
while(true){
List<Integer> temp=new ArrayList<>();
for(int i=1;i<=n;i++){
if(nb[i]!=-1){
int x=bfs(i,n);
if(x==1){
temp.add(i);
}
}
}
if(temp.size()==0) break;
for(int j:temp)
{
vis[j]=-1;
nb[j]=-1;
}
temp.clear();
res++;
}
out.println(res);
out.close();
}
}
class Node{
List<Integer> adj =new ArrayList<>();
}
class FastScanner{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st =new StringTokenizer("");
String next(){
if(!st.hasMoreTokens()){
try{
st=new StringTokenizer(br.readLine());
}
catch(Exception e){
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 6022929d6de3f8929fc958503daf4f3c | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Shoe {
private int v;
private LinkedList<Integer> adj[];
public Shoe(int v) {
this.v=v;
adj=new LinkedList[v+1];
for(int i=0;i<v+1;i++) {
adj[i]=new LinkedList<>();
}
}
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m, total=0;
int n=sc.nextInt();
Shoe g = new Shoe( n);
m = sc.nextInt();
boolean visited[] = new boolean[n+1];
Arrays.fill(visited, false);
int indegree[] = new int[n+1];
for(int i=1;i<=n;i++) {
indegree[i]=0;
}
int i=0;
while( i!=m) {
int a= sc.nextInt();
int b= sc.nextInt();
indegree[a]++;
indegree[b]++;
g.addEdge(a, b);
i++;
}
ArrayList<Integer> res = new ArrayList<>();
System.out.println(g.calculateScore(visited,indegree,total,res));
}
private int calculateScore(boolean[] visited,int[] indegree,int total,ArrayList<Integer> res) {
boolean flag=true;
for(int i=1;i<v+1;i++) {
if(indegree[i]==1 && !visited[i]) {
res.add(i);
flag=false;
visited[i]=true;
}
}
if(!flag) {
total++;
for(int j :res) {
for(int k:adj[j]) {
if(!visited[k]) {
indegree[k]--;
}
}
}
res.clear();
return calculateScore(visited, indegree, total,new ArrayList<Integer>());
}
else {
return total;
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | c33ba73daf0c952a58988a0c48288bfe | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Test2
{
static class pair{
int f; int s;
protected pair(int f,int s){
this.f=f;this.s=s;
}
}
public static void main(String[] args)throws Exception {
reader in = new reader(System.in);
int n=in.nextInt();int m=in.nextInt();
boolean arr[][]= new boolean[101][101];
boolean cant[]= new boolean[101];
ArrayList<pair> list= new ArrayList<pair>();int o= 0;
for(int i=0;i<m;i++){
int x=in.nextInt()-1;
int y=in.nextInt()-1;
arr[x][y]=true;
arr[y][x]=true;
}
int ans=0;
for(int i=0;i<n;i++){boolean t=false;
//if(!cant[i])
for(int j=0;j<n;j++){
int c=0;int l=0;int d=0;
for(int k=0;k<n;k++){
if(c>1)
break;
if(arr[j][k]){
c++;l=j;d=k;}
}
if(c==1){
arr[l][d]=false;
list.add(new pair(l,d));
cant[l]=true;
t=true;
}
}
if(t){
ans++;for(;o<list.size();o++){
arr[list.get(o).s][list.get(o).f]=false;
}}
}
System.out.println(ans);
}
static class reader{
BufferedReader in ;
StringTokenizer tok;
public reader(InputStream stream){
in = new BufferedReader(new InputStreamReader(stream));
tok=null;
}
String next()throws Exception{
while(tok==null||!tok.hasMoreElements()){
tok=new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int nextInt()throws Exception{
return Integer.parseInt(next());
}
long nextLong() throws Exception{
return Long.parseLong(next());
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 8a4d9dc8ad059f439f23b9c546d795be | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class dfs {
// better solution for less steps
public static int gcdFast(int x, int y) {
if (y == 0) {
return x;
} else {
return gcdFast(y, x % y);
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // number of nodes
int m = sc.nextInt(); // number of edges
int arraylist[][] = new int[n][n];
for (int i = 0; i < m; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
arraylist[x][y] = 1;
arraylist[y][x] = 1;
}
boolean f = true;
int answ = 0;
while (f) {
f = false;
Queue<Integer> qu = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
int neighbour = 0;
int idx = 0;
for (int j = 0; j < n; j++) {
if (arraylist[i][j] == 1) {
neighbour += arraylist[i][j];
idx = j;
}
}
if (neighbour == 1) {
qu.add(i);
qu.add(idx);
f = true;
}
}
while (!qu.isEmpty()) {
int u = qu.poll();
int v = qu.poll();
arraylist[u][v] = 0;
arraylist[v][u] = 0;
}
if (f) {
answ++;
}
}
System.out.println(answ);
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public 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();
}
public int[] nextArr(int n) throws IOException {
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 05b123a471efb9f497edf318e6efdb9d | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class CF129_D2_B {
private static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
addEdge(x - 1, y - 1);
}
int count = 0;
int groups = 0;
do {
count = 0;
ArrayList<Integer> toRemove = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (graph.get(i).size() == 1) {
toRemove.add(i);
count++;
}
}
for (int i : toRemove) {
if (graph.get(i).size() > 0) {
int x = graph.get(i).get(0);
graph.get(i).remove(0);
graph.get(x).remove((Integer) i);
}
}
if (count != 0) {
groups++;
}
} while (count > 0);
System.out.println(groups);
}
private static void addEdge(int x, int y) {
graph.get(x).add(y);
graph.get(y).add(x);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | ce2550642a3e0530a815cba9f1c3297a | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class Bshoo {
private static final Scanner in = new Scanner(System.in);
private static int N,M,l,k,X[],O[],V,sum;
private static List<Integer> gr[];
private static boolean B [];
public static void main(String[] args) {
N=in.nextInt();M=in.nextInt();
X=new int [N+1];B=new boolean[N+1];O=new int [N+1];
gr=new List[N+1];
for(int i =0;i<=N;i++){gr[i]=new ArrayList();}
for(int i =0;i<M;i++){
l=in.nextInt();k=in.nextInt();
X[l]++;X[k]++;O[l]++;O[k]++;
gr[l].add(k);
gr[k].add(l);}
for(int i =0;i<N+1;i++)
{dfs();
if(V>0){sum++;V=0;B=new boolean[N+1];X=O;}
}
System.out.println(sum);
}
static void dfs()
{for(int i =0;i<N+1;i++){
if(X[i]==1&&!B[i]){O[i]=0;V++;B[i]=true;
for(int j:gr[i]){
{O[j]--;B[j]=true;}}}}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 38b160e5ccd04948338d08b93d877220 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
int n= leer.nextInt();
int m= leer.nextInt();
Lista A []= new Lista[n+1];
int N [] = new int [n+1];
for (int i = 1; i <=n; i++)
A[i]=new Lista();
for (int i = 0; i < m; i++) {
int x = leer.nextInt();
int y = leer.nextInt();
A[x].add(y);
A[y].add(x);
N[x]++;N[y]++;
}
Lista P;
int h=0;
boolean Visitados[]= new boolean [n+1];
while(true){P=new Lista();
for (int i = 1; i <=n; i++) {
if(N[i]==1 && !Visitados[i]){P.add(i);Visitados[i]=true;}
}
Nodo C = P.ini;
if(P.n>0){
while(C!=null){
Nodo T = A[C.n].ini;
while(T!=null){
N[T.n]--;
T=T.sig;
}
C=C.sig;
}
}else break;
h++;
}
System.out.println(h);
}
static class Nodo{
int n;
Nodo sig;
public Nodo(int x){
n=x;
sig=null;
}
}
static class Lista{
Nodo ini;
int n;
public Lista(){
ini=null;n=0;
}
public void add(int x){
Nodo A = new Nodo(x);
A.sig=ini;
ini=A;
n++;
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 30aae169ea8c993231efd3a46ac600ac | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | // δ½θ
οΌζ¨ζηε
η
// try FastScanner when done
import java.util.*;
public class student {
static ArrayList<Integer>[] adj;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
adj = new ArrayList[n];
for(int i=0;i<n;i++) {
adj[i] = new ArrayList<Integer>();
}
while(m-->0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
adj[x].add(y);
adj[y].add(x);
}
int ans = 0;
while(true) {
ArrayList<Integer> r = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if(adj[i].size() == 1) {
r.add(i);
adj[i].clear();
}
}
if(r.size() == 0) {
break;
}
else {
for(int i=0;i<r.size();i++) {
for(int j=0;j<n;j++) {
if(adj[j].contains(r.get(i))) {
adj[j].remove(r.get(i));
}
}
}
ans++;
}
}
System.out.println(ans);
sc.close();
}
}
/*
6 3
1 2
2 3
3 4
*/ | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 53a25de37a474e7393c85907f9534de4 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.util.*;
public class student {
static class FastScanner {
static final int DEFAULT_BUFF = 1024, EOF = -1, INT_MIN = 48, INT_MAX = 57;
static final byte NEG = 45;
static final int[] ints = new int[58];
static {
int value = 0;
for (int i = 48; i < 58; i++) {
ints[i] = value++;
}
}
InputStream stream;
byte[] buff;
int buffPtr;
public FastScanner(InputStream stream) {
this.stream = stream;
this.buff = new byte[DEFAULT_BUFF];
this.buffPtr = -1;
}
public int nextInt() throws IOException {
int val = 0;
int sign = readNonDigits();
while (isDigit(buff[buffPtr]) && buff[buffPtr] != EOF) {
val = (val << 3) + (val << 1) + ints[buff[buffPtr]];
buffPtr++;
if (buffPtr == buff.length) {
updateBuff();
}
}
return val*sign;
}
private int readNonDigits() throws IOException {
if (buffPtr == -1 || buffPtr == buff.length) {
updateBuff();
}
if (buff[buffPtr] == EOF) {
throw new IOException("End of stream reached");
}
int signByte = -1;
while (!isDigit(buff[buffPtr])) {
signByte = buff[buffPtr];
buffPtr++;
if (buffPtr >= buff.length) {
updateBuff();
}
if (buff[buffPtr] == EOF) {
throw new IOException("End of stream reached");
}
}
if(signByte == NEG) return -1;
return 1;
}
public void close() throws IOException {
stream.close();
}
private boolean isDigit(int b) {
return b >= INT_MIN && b <= INT_MAX;
}
private void updateBuff() throws IOException {
buffPtr = 0;
stream.read(buff);
}
}
static ArrayList<Integer>[] adj;
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
adj = new ArrayList[n];
for(int i=0;i<n;i++) {
adj[i] = new ArrayList<Integer>();
}
while(m-->0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
adj[x].add(y);
adj[y].add(x);
}
int ans = 0;
while(true) {
ArrayList<Integer> r = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if(adj[i].size() == 1) {
r.add(i);
adj[i].clear();
}
}
if(r.size() == 0) {
break;
}
else {
for(int i=0;i<r.size();i++) {
for(int j=0;j<n;j++) {
if(adj[j].contains(r.get(i))) {
adj[j].remove(r.get(i));
}
}
}
ans++;
}
}
System.out.println(ans);
sc.close();
}
}
/*
6 3
1 2
2 3
3 4
*/ | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 7c5fd91e06d128b86cc6e0f25dbee0e6 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes |
//import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Scanner;
import javax.xml.transform.Templates;
//import java.util.Collection;
//import java.util.Collections;
public class test {
static public void main(String phone[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[110];
int[][] grid = new int[100000][2];
for (int i = 0; i < m; i++) {
int x = sc.nextInt(), y = sc.nextInt();
arr[x]++;
arr[y]++;
grid[i][0] = x;
grid[i][1] = y;
}
boolean f = true;
int cnt = 0;
while (f) {
ArrayList<Integer> temp = new ArrayList<>();
f = false;
for (int i = 1; i <= n; i++) {
if (arr[i] == 1) {
arr[i] = 0;
f = true;
for (int l = 0; l < m; l++) {
if (grid[l][0] == i && arr[grid[l][1]]!=0 ) {
temp.add(grid[l][1]);
break;
}
if (grid[l][1] == i && arr[grid[l][0]]!=0) {
temp.add(grid[l][0]);
break;
}
}
}
}
if (f)
cnt++;
for (int i = 0; i < temp.size(); i++) {
arr[temp.get(i)]--;
}
}
System.out.println(cnt);
}
}
/*
62 6
29 51
29 55
4 12
29 11
51 19
16 7
*/
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 5cd1894b28be3cfbb9e9fe2a91d4945c | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class test {
static public void main(String phone[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[110];
int[][] grid = new int[10005][2];
for (int i = 0; i < m; i++) {
int x = sc.nextInt(), y = sc.nextInt();
arr[x]++;
arr[y]++;
grid[i][0] = x;
grid[i][1] = y;
}
boolean f = true;
int cnt = 0;
while (f) {
ArrayList<Integer> temp = new ArrayList<>();
f = false;
for (int i = 1; i <= n; i++) {
if (arr[i] == 1) {
arr[i] = 0;
f = true;
for (int l = 0; l < m; l++) {
if (grid[l][0] == i && arr[grid[l][1]]!=0 ) {
temp.add(grid[l][1]);
break;
}
if (grid[l][1] == i && arr[grid[l][0]]!=0) {
temp.add(grid[l][0]);
break;
}
}
}
}
if (f)
cnt++;
for (int i = 0; i < temp.size(); i++) {
arr[temp.get(i)]--;
}
}
System.out.println(cnt);
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | d2de1fdfdaa0918d34fb55a68c1e2ac3 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
/**
* @author mohanad
*
*/
public class Div2_129B {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String nmz[] = bf.readLine().split(" ");
int n = Integer.parseInt(nmz[0]);
int m = Integer.parseInt(nmz[1]);
List arr[] = new List[n + 1];
for (int i = 0; i <= n; ++i) {
arr[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; ++i) {
String ab[] = bf.readLine().split(" ");
int a = Integer.parseInt(ab[0]);
int b = Integer.parseInt(ab[1]);
arr[a].add(b);
arr[b].add(a);
}
boolean flag = true;
int ans = 0;
while (flag) {
flag = false;
boolean visited[] = new boolean[n + 1];
for (int i = 1; i <= n; ++i) {
if (!visited[i] && arr[i].size() == 1) {
int num = (int) arr[i].get(0);
arr[i].remove(0);
visited[num] = true;
flag=true;
;
for (int j = 0; j < arr[num].size(); ++j)
if ((int) arr[num].get(j) == i) {
arr[num].remove(j);
break;
}
}
}
ans += flag ? 1 : 0;
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | e42b7a4b77b9d23990b33de6a995d5f3 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
/**
*
* @author mohanad elmaghrby
*/
public class Div2_129B {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan= new Scanner (System.in);
int n =scan.nextInt();
int m=scan.nextInt();
int count[]=new int[n+1];
boolean visited[]=new boolean[n+1];
List arr[]=new List[n+1];
for (int i = 0 ; i < m ; ++i){
int a=scan.nextInt();
int b=scan.nextInt();
++count[a];
++count[b];
if (!visited[a]){
visited[a]=true;
arr[a]=new LinkedList();
}
if (!visited[b]){
visited[b]=true;
arr[b]=new LinkedList();
}
arr[a].add(b);
arr[b].add(a);
}
int ans=0;
boolean flag=true;
while (flag ){
flag=false;
boolean visit[]=new boolean[n+1];
for (int i = 1 ; i <=n ; ++i){
if ( !visit[i]&&count[i]==1){
count[i]=0;
int con=(int) arr[i].remove(0);
for (int s= 0 ; s<arr[con].size() ; ++s)
if((int)arr[con].get(s)==i)
arr[con].remove(s);
count[con]--;
flag=true;
visit[con]=true;
}
}
if (flag)
++ans;
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 2b6d270044e4e050d9a5716a2e62afef | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.util.*;
import java.io.*;
public class StudentsandShoelaces {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve() throws IOException {
int n= ni(), m= ni();
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
for(int i=0;i<=n;i++)
arrayLists.add(new ArrayList<>());
for(int i=0;i<m;i++)
{
int a= ni(), b= ni();
arrayLists.get(a).add(b);
arrayLists.get(b).add(a);
}
boolean[] expelled= new boolean[n+1];
int ans=0;
while(true)
{
boolean[] visited= new boolean[n+1];
Queue<Integer> queue = new LinkedList<>();
int count_expelled = 0;
ArrayList<Integer> list = new ArrayList<>();
for(int i=1;i<=n;i++)
{
if(!expelled[i] && !visited[i]) {
queue.add(i);
visited[i] = true;
while (!queue.isEmpty()) {
int curr = queue.poll();
int expell= 0;
for (int ii : arrayLists.get(curr)) {
if (expelled[ii]) continue;
expell++;
if (visited[ii]) continue;
queue.add(ii);
visited[ii] = true;
}
if(expell== 1)
{
count_expelled++;
//out.println("expell "+ans+" ="+curr);
list.add(curr);
}
}
}
}
for(int i: list)
expelled[i]= true;
if(count_expelled==0)
break;
ans++;
}
out.println(ans);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new StudentsandShoelaces().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 7da4c261ca17fdd73076b7982c97ab3c | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Map<Integer, Integer>counts = new HashMap<Integer, Integer>();
int [][] pairs = new int[n + 1][n + 1];
int a,b;
for(int i = 0; i < m; i++){
a = scanner.nextInt();
b = scanner.nextInt();
pairs[a][b] = 1;
pairs[b][a] = 1;
if(counts.containsKey(a)){
counts.put(a, counts.get(a) + 1);
}else{
counts.put(a,1);
}
if(counts.containsKey(b)){
counts.put(b, counts.get(b) + 1);
}else{
counts.put(b,1);
}
}
int count = 0, groups = 0;
while(counts.size() > 1){
Set<Integer>removed = new HashSet<Integer>();
count = 0;
for(Entry<Integer, Integer> entry : counts.entrySet()){
if(entry.getValue() < 2 && entry.getValue() > 0){
removed.add(entry.getKey());
count++;
}
}
for(Iterator<Integer> it = removed.iterator(); it.hasNext(); ){
int x = it.next();
for(int i = 1; i <= n + 1; i++){
if(i == x){
for(int j = 1; j < n+1; j++){
if(1 == pairs[i][j]){
counts.put(j, counts.get(j) - 1);
pairs[i][j] = 0;
pairs[j][i] = 0;
}
}
}
}
}
counts.keySet().removeAll(removed);
if(count >= 1){
groups++;
}else{
break;
}
}
System.out.println(groups);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 63e4f02ecb1e2e4aa1200acb84f914f2 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException{
Scanner sc=new Scanner(System.in);
int t=1;//sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int m=sc.nextInt();
HashSet<Integer>[] set=new HashSet[n];
for(int i=0;i<n;i++) {
set[i]=new HashSet<>();
}
for(int i=0;i<m;i++) {
int u=sc.nextInt();
int v=sc.nextInt();
set[u-1].add(v-1);
set[v-1].add(u-1);
}
int count=0;
while(true) {
int val=0;
ArrayList<Integer> index=new ArrayList<>();
ArrayList<Integer> remove=new ArrayList<>();
for (int i=0;i<n;i++) {
if(set[i].size()==1) {
val++;
for (int k:set[i]) {
index.add(k);
remove.add(i);
}
}
}
if(val==0) break;
count+=1;
for (int i=0;i<index.size();i++) {
set[index.get(i)].remove(remove.get(i));
set[remove.get(i)].remove(index.get(i));
}
}
System.out.println(count);
}
}
static boolean isvalid(int x,int y,int n) {
if(x<0 || y<0 || x>n-1 || y>n-1) return false;
return true;
}
static class Reader{
BufferedReader reader;
Reader(){
reader=new BufferedReader(new InputStreamReader(System.in));
}
int nextInt() throws IOException{
String in=reader.readLine().trim();
return Integer.parseInt(in);
}
long nextLong() throws IOException{
String in=reader.readLine().trim();
return Long.parseLong(in);
}
String next() throws IOException{
return reader.readLine().trim();
}
String[] stringArray() throws IOException{
return reader.readLine().trim().split("\\s+");
}
int[] intArray() throws IOException{
String[] inp=this.stringArray();
int[] arr=new int[inp.length];
int i=0;
for(String s:inp) {
arr[i++]=Integer.parseInt(s);
}
return arr;
}
}
}
/*e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6*/
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 02676d374c665755dae02dd9bf23dada | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | import java.io.*;
import java.util.*;
public class B_StudentsShoelaces {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
private static class Solver {
private void solve(InputReader inp, PrintWriter out) {
int n = inp.nextInt(), m = inp.nextInt(), res = 0;
ArrayList<int[]> edges = new ArrayList<>(n);
for (int i = 0; i < m; i++) {
int u = inp.nextInt() - 1, v = inp.nextInt() - 1;
edges.add(new int[]{u, v});
}
boolean change;
do {
int[] degree = new int[n];
for (int[] e: edges) {
degree[e[0]]++;
degree[e[1]]++;
}
HashSet<Integer> kicked = new HashSet<>();
for (int i = 0; i < n; i++) if (degree[i] == 1) kicked.add(i);
edges.removeIf(a -> kicked.contains(a[0]) || kicked.contains(a[1]));
change = kicked.size() > 0;
if (change) res++;
} while (change);
out.println(res);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 9d9ebd4c90e7fdb3bb47ec5d22104a7f | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | //package competitive;
import java.util.*;
import java.io.*;
public class B129 {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
String str[]= s.trim().split(" ");
int n=Integer.parseInt(str[0]),i,x,y;
int m=Integer.parseInt(str[1]);
//ArrayList<Integer> x=new ArrayList<Integer>();
ArrayList<Integer> [] adj= new ArrayList [n+1];
for(i=1;i<=n;++i)
{
adj[i]=new ArrayList<Integer>();
}
for(i=0;i<m;++i)
{
s=br.readLine();
str= s.trim().split(" ");
x=Integer.parseInt(str[0]);
y=Integer.parseInt(str[1]);
adj[x].add(y);
adj[y].add(x);
}
boolean flag=true;int ans=0;
while(true)
{ ArrayList<Integer> temp=new ArrayList<Integer>();
for(i=1;i<=n;++i)
{
if(adj[i].size()==1)
{
temp.add(i);
}
}
// System.out.println("temp"+temp.size());
if(temp.size()==0)
break;
++ans;
// Integer obj,obj1;
for(i=0;i<temp.size();++i)
{
x=temp.get(i);//[i];
//System.out.println("x"+x+"size"+adj[x].size());
y=5;
if(adj[x].size()>0)
{ //System.out.println("OKKK"+adj[x].size());
y=adj[x].get(0);
adj[x].remove(new Integer(y));
}
// System.out.println("HMMM"+adj[x].size());
if(adj[y].size()>0)
adj[y].remove(new Integer(x));
}
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 93ae9f0f010321e006214d7b4098ede6 | train_003.jsonl | 1321337400 | Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club. | 256 megabytes | //package competitive;
import java.util.*;
import java.io.*;
public class B129 {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
String str[]= s.trim().split(" ");
int n=Integer.parseInt(str[0]),i,x,y;
int m=Integer.parseInt(str[1]);
//ArrayList<Integer> x=new ArrayList<Integer>();
ArrayList<Integer> [] adj= new ArrayList [n+1];
for(i=1;i<=n;++i)
{
adj[i]=new ArrayList<Integer>();
}
for(i=0;i<m;++i)
{
s=br.readLine();
str= s.trim().split(" ");
x=Integer.parseInt(str[0]);
y=Integer.parseInt(str[1]);
adj[x].add(y);
adj[y].add(x);
}
boolean flag=true;int ans=0;
while(true)
{ ArrayList<Integer> temp=new ArrayList<Integer>();
for(i=1;i<=n;++i)
{
if(adj[i].size()==1)
{
temp.add(i);
}
}
// System.out.println("temp"+temp.size());
if(temp.size()==0)
break;
++ans;
// Integer obj,obj1;
int sz=temp.size();
for(i=0;i<sz;++i)
{
x=temp.get(i);//[i];
//System.out.println("x"+x+"size"+adj[x].size());
y=5;
if(adj[x].size()>0)
{ //System.out.println("OKKK"+adj[x].size());
y=adj[x].get(0);
adj[x].remove(new Integer(y));
}
// System.out.println("HMMM"+adj[x].size());
if(adj[y].size()>0)
adj[y].remove(new Integer(x));
}
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"] | 2 seconds | ["0", "2", "1"] | NoteIn the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f8315dc903b0542c453cab4577bcb20d | The first line contains two integers n and m β the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1ββ€βa,βbββ€βn,βaββ βb). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself. | 1,200 | Print the single number β the number of groups of students that will be kicked out from the club. | standard output | |
PASSED | 4d3bf9c928423b1eb23445ebd754400f | train_003.jsonl | 1462633500 | Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1,βv2,β...,βvn that v1β=βa, vnβ=βb and there is a road between vi and viβ+β1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1,βu2,β...,βun that u1β=βc, unβ=βd and there is a road between ui and uiβ+β1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1,β...,βvn) and (u1,β...,βun) to satisfy all the given conditions? Find any solution or print -1 if it's impossible. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class B {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int k = nextInt();
int a = nextInt();
int b = nextInt();
int c = nextInt();
int d = nextInt();
if (n==4 || k < n+1) {
System.out.println(-1);
return;
}
ArrayList<Integer> last = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i != a && i != b && i != c && i != d)
last.add(i);
}
pw.print(a+" "+c+" ");
for (int i : last) {
pw.print(i+" ");
}
pw.println(d+" "+b);
pw.print(c+" "+a+" ");
for (int i : last) {
pw.print(i+" ");
}
pw.println(b+" "+d);
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["7 11\n2 4 7 3", "1000 999\n10 20 30 40"] | 2 seconds | ["2 7 1 3 6 5 4\n7 1 5 4 6 2 3", "-1"] | NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3. | Java 7 | standard input | [
"constructive algorithms",
"graphs"
] | 6b398790adbd26dd9af64e9086e38f7f | The first line of the input contains two integers n and k (4ββ€βnββ€β1000, nβ-β1ββ€βkββ€β2nβ-β2)Β β the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1ββ€βa,βb,βc,βdββ€βn). | 1,600 | Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1,βv2,β...,βvn where v1β=βa and vnβ=βb. The second line should contain n distinct integers u1,βu2,β...,βun where u1β=βc and unβ=βd. Two paths generate at most 2nβ-β2 roads: (v1,βv2),β(v2,βv3),β...,β(vnβ-β1,βvn),β(u1,βu2),β(u2,βu3),β...,β(unβ-β1,βun). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x,βy) and (y,βx) are the same road. | standard output | |
PASSED | 338af97d6e5f1073b71bcd1436f78cc7 | train_003.jsonl | 1462633500 | Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1,βv2,β...,βvn that v1β=βa, vnβ=βb and there is a road between vi and viβ+β1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1,βu2,β...,βun that u1β=βc, unβ=βd and there is a road between ui and uiβ+β1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1,β...,βvn) and (u1,β...,βun) to satisfy all the given conditions? Find any solution or print -1 if it's impossible. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Codeforces674B {
public static void main(String[] args) {
try {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
if(n == 4 || k < n + 1) {
System.out.println(-1);
}
else {
StringBuffer s = new StringBuffer();
for(int i = 1; i <= n; i++) {
if(i == a || i == b || i == c || i == d)
continue;
s.append(i + " ");
}
String v = a + " " + c + " " + s.toString() + d + " " + b;
String u = c + " " + a + " " + s.toString() + b + " " + d;
System.out.println(v);
System.out.println(u);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
| Java | ["7 11\n2 4 7 3", "1000 999\n10 20 30 40"] | 2 seconds | ["2 7 1 3 6 5 4\n7 1 5 4 6 2 3", "-1"] | NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3. | Java 7 | standard input | [
"constructive algorithms",
"graphs"
] | 6b398790adbd26dd9af64e9086e38f7f | The first line of the input contains two integers n and k (4ββ€βnββ€β1000, nβ-β1ββ€βkββ€β2nβ-β2)Β β the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1ββ€βa,βb,βc,βdββ€βn). | 1,600 | Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1,βv2,β...,βvn where v1β=βa and vnβ=βb. The second line should contain n distinct integers u1,βu2,β...,βun where u1β=βc and unβ=βd. Two paths generate at most 2nβ-β2 roads: (v1,βv2),β(v2,βv3),β...,β(vnβ-β1,βvn),β(u1,βu2),β(u2,βu3),β...,β(unβ-β1,βun). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x,βy) and (y,βx) are the same road. | standard output | |
PASSED | f29f650115b950fbfca483bb4f7029a2 | train_003.jsonl | 1462633500 | Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1,βv2,β...,βvn that v1β=βa, vnβ=βb and there is a road between vi and viβ+β1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1,βu2,β...,βun that u1β=βc, unβ=βd and there is a road between ui and uiβ+β1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1,β...,βvn) and (u1,β...,βun) to satisfy all the given conditions? Find any solution or print -1 if it's impossible. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class CodeB {
private static final boolean SHOULD_BUFFER_OUTPUT = false;
static final SuperWriter sw = new SuperWriter(System.out);
static final SuperScanner sc = new SuperScanner();
public static void main() {
int n = sc.nextInt();
int k = sc.nextInt();
if (n == 4) {
sw.printLine(-1);
return;
}
if (k < n + 1) {
sw.printLine(-1);
return;
}
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
TreeSet<Integer> values = new TreeSet<>();
for (int i = 1; i <= n; i++) {
values.add(i);
}
values.remove(a);
values.remove(b);
values.remove(c);
values.remove(d);
ArrayList<Integer> cities = new ArrayList<>();
cities.add(a);
cities.add(c);
while (!values.isEmpty()) {
cities.add(values.pollFirst());
}
cities.add(d);
cities.add(b);
sw.printLine(cities);
ArrayList<Integer> pathC = new ArrayList<>();
pathC.add(c);
pathC.add(a);
for (int i = 2; i < cities.size() - 2; i++) {
pathC.add(cities.get(i));
}
pathC.add(b);
pathC.add(d);
sw.printLine(pathC);
}
static class LineScanner extends Scanner {
private StringTokenizer st;
public LineScanner(String input) {
st = new StringTokenizer(input);
}
@Override
public String next() {
return st.hasMoreTokens() ? st.nextToken() : null;
}
@Override
public String nextLine() {
throw new RuntimeException("not supported");
}
public boolean hasNext() {
return st.hasMoreTokens();
}
private final ArrayList<Object> temp = new ArrayList<Object>();
private void fillTemp() {
while (st.hasMoreTokens()) {
temp.add(st.nextToken());
}
}
public String[] asStringArray() {
fillTemp();
String[] answer = new String[temp.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = (String) temp.get(i);
}
temp.clear();
return answer;
}
public int[] asIntArray() {
fillTemp();
int[] answer = new int[temp.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = Integer.parseInt((String) temp.get(i));
}
temp.clear();
return answer;
}
public long[] asLongArray() {
fillTemp();
long[] answer = new long[temp.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = Long.parseLong((String) temp.get(i));
}
temp.clear();
return answer;
}
public double[] asDoubleArray() {
fillTemp();
double[] answer = new double[temp.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = Double.parseDouble((String) temp.get(i));
}
temp.clear();
return answer;
}
}
static class SuperScanner extends Scanner {
private InputStream stream;
private byte[] buf = new byte[8096];
private int curChar;
private int numChars;
public SuperScanner() {
this.stream = System.in;
}
public int read() {
if (numChars == -1)
return -1;
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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public static boolean isLineEnd(int c) {
return c == '\n' || c == -1;
}
private final StringBuilder sb = new StringBuilder();
@Override
public String next() {
int c = read();
while (isWhitespace(c)) {
if (c == -1) {
return null;
}
c = read();
}
sb.setLength(0);
do {
sb.append((char) c);
c = read();
} while (!isWhitespace(c));
return sb.toString();
}
@Override
public String nextLine() {
sb.setLength(0);
int c;
while (true) {
c = read();
if (!isLineEnd(c)) {
sb.append((char) c);
} else {
break;
}
}
if (c == -1 && sb.length() == 0) {
return null;
} else {
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\r') {
return sb.substring(0, sb.length() - 1);
} else {
return sb.toString();
}
}
}
public LineScanner nextLineScanner() {
String line = nextLine();
if (line == null) {
return null;
} else {
return new LineScanner(line);
}
}
public LineScanner nextNonEmptyLineScanner() {
while (true) {
String line = nextLine();
if (line == null) {
return null;
} else if (!line.isEmpty()) {
return new LineScanner(line);
}
}
}
@Override
public int nextInt() {
int c = read();
while (isWhitespace(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 = (res << 3) + (res << 1);
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
@Override
public long nextLong() {
int c = read();
while (isWhitespace(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 = (res << 3) + (res << 1);
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
static abstract class Scanner {
public abstract String next();
public abstract String nextLine();
public int nextIntOrQuit() {
Integer n = nextInteger();
if (n == null) {
sw.close();
System.exit(0);
}
return n.intValue();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n) {
double[] res = new double[n];
for (int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array) {
Integer[] vals = new Integer[array.length];
for (int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for (int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array) {
Long[] vals = new Long[array.length];
for (int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for (int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array) {
Double[] vals = new Double[array.length];
for (int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for (int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n) {
String[] vals = new String[n];
for (int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
public Integer nextInteger() {
String s = next();
if (s == null)
return null;
return Integer.parseInt(s);
}
public int[][] nextIntMatrix(int n, int m) {
int[][] ans = new int[n][];
for (int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
public char[][] nextGrid(int r) {
char[][] grid = new char[r][];
for (int i = 0; i < r; i++)
grid[i] = next().toCharArray();
return grid;
}
public static <T> T fill(T arreglo, int val) {
if (arreglo instanceof Object[]) {
Object[] a = (Object[]) arreglo;
for (Object x : a)
fill(x, val);
} else if (arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if (arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if (arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
public <T> T[] nextObjectArray(Class<T> clazz, int size) {
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
for (int c = 0; c < 3; c++) {
Constructor<T> constructor;
try {
if (c == 0)
constructor = clazz.getDeclaredConstructor(Scanner.class,
Integer.TYPE);
else if (c == 1)
constructor = clazz.getDeclaredConstructor(Scanner.class);
else
constructor = clazz.getDeclaredConstructor();
} catch (Exception e) {
continue;
}
try {
for (int i = 0; i < result.length; i++) {
if (c == 0)
result[i] = constructor.newInstance(this, i);
else if (c == 1)
result[i] = constructor.newInstance(this);
else
result[i] = constructor.newInstance();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
throw new RuntimeException("Constructor not found");
}
public Collection<Integer> wrap(int[] as) {
ArrayList<Integer> ans = new ArrayList<Integer>();
for (int i : as)
ans.add(i);
return ans;
}
public int[] unwrap(Collection<Integer> collection) {
int[] vals = new int[collection.size()];
int index = 0;
for (int i : collection)
vals[index++] = i;
return vals;
}
int testCases = Integer.MIN_VALUE;
boolean testCases() {
if (testCases == Integer.MIN_VALUE) {
testCases = nextInt();
}
return --testCases >= 0;
}
}
static class SuperWriter {
private final PrintWriter writer;
public SuperWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public SuperWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.flush();
writer.close();
}
public void printLine(String line) {
writer.println(line);
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public void printLine(int... vals) {
if (vals.length == 0) {
writer.println();
} else {
writer.print(vals[0]);
for (int i = 1; i < vals.length; i++)
writer.print(" ".concat(String.valueOf(vals[i])));
writer.println();
}
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public void printLine(long... vals) {
if (vals.length == 0) {
writer.println();
} else {
writer.print(vals[0]);
for (int i = 1; i < vals.length; i++)
writer.print(" ".concat(String.valueOf(vals[i])));
writer.println();
}
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public void printLine(double... vals) {
if (vals.length == 0) {
writer.println();
} else {
writer.print(vals[0]);
for (int i = 1; i < vals.length; i++)
writer.print(" ".concat(String.valueOf(vals[i])));
writer.println();
}
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public void printLine(int prec, double... vals) {
if (vals.length == 0) {
writer.println();
} else {
String precision = "%." + prec + "f";
writer.print(String.format(precision, vals[0]).replace(',', '.'));
precision = " " + precision;
for (int i = 1; i < vals.length; i++)
writer.print(String.format(precision, vals[i]).replace(',', '.'));
writer.println();
}
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public <E> void printLine(Collection<E> vals) {
if (vals.size() == 0) {
writer.println();
} else {
int i = 0;
for (E val : vals) {
if (i++ == 0) {
writer.print(val.toString());
} else {
writer.print(" ".concat(val.toString()));
}
}
writer.println();
}
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public void printSimple(String value) {
writer.print(value);
if (!SHOULD_BUFFER_OUTPUT) {
writer.flush();
}
}
public boolean ifZeroExit(Number... values) {
for (Number number : values) {
if (number.doubleValue() != 0.0d || number.longValue() != 0) {
return false;
}
}
close();
System.exit(0);
return true;
}
}
public static void main(String[] args) {
main();
sw.close();
}
}
| Java | ["7 11\n2 4 7 3", "1000 999\n10 20 30 40"] | 2 seconds | ["2 7 1 3 6 5 4\n7 1 5 4 6 2 3", "-1"] | NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3. | Java 7 | standard input | [
"constructive algorithms",
"graphs"
] | 6b398790adbd26dd9af64e9086e38f7f | The first line of the input contains two integers n and k (4ββ€βnββ€β1000, nβ-β1ββ€βkββ€β2nβ-β2)Β β the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1ββ€βa,βb,βc,βdββ€βn). | 1,600 | Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1,βv2,β...,βvn where v1β=βa and vnβ=βb. The second line should contain n distinct integers u1,βu2,β...,βun where u1β=βc and unβ=βd. Two paths generate at most 2nβ-β2 roads: (v1,βv2),β(v2,βv3),β...,β(vnβ-β1,βvn),β(u1,βu2),β(u2,βu3),β...,β(unβ-β1,βun). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x,βy) and (y,βx) are the same road. | standard output | |
PASSED | 9bb0ffc87be4be1faca9f67366727ec0 | train_003.jsonl | 1566135900 | You are given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \cdot a_2$$$ $$$\dots$$$ $$$\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\cdot (-1) \cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that? | 256 megabytes |
import java.math.*;
import java.util.*;
public class BruteForce {
public static Scanner in =new Scanner(System.in);
public static void main(String[] args){
ArrayList<Integer> neg=new ArrayList<Integer>();
ArrayList<Integer> pos=new ArrayList<Integer>();
int n=in.nextInt();
for(int i=0;i<n;i++){
int cur=in.nextInt();
if(cur>=0)
pos.add(cur);
else
neg.add(cur);
}
long cost=0;
if(neg.size()%2==0){
for(int i=0;i<neg.size();i++){
int dif=Math.abs(neg.get(i))-1;
cost+=dif;
}
for(int i=0;i<pos.size();i++){
int dif=Math.abs(1-pos.get(i));
cost+=dif;
}
}
else{
Collections.sort(neg);
Collections.sort(pos);
if(pos.size()==0){
for(int i=0;i<neg.size();i++){
int dif=Math.abs(neg.get(i))-1;
cost+=dif;
}
/*for(int i=0;i<pos.size();i++){
int dif=Math.abs(1-pos.get(i));
cost+=dif;
}*/
cost+=2;
}
else{
for(int i=0;i<neg.size()-1;i++){
int dif=-1-neg.get(i);
cost+=dif;
}
for(int i=1;i<pos.size();i++){
int dif=Math.abs(1-pos.get(i));
cost+=dif;
}
long costA=cost;
long costB=cost;
int a=1-neg.get(neg.size()-1);
int b=Math.abs(1-pos.get(0));
costA+=(a+b);
int x=pos.get(0)+1;
int y=Math.abs(neg.get(neg.size()-1))-1;
costB+=(x+y);
//System.out.println(Math.min(costA,costB));
cost=Math.min(costA,costB);
}
}
System.out.println(cost);
}
} | Java | ["2\n-1 1", "4\n0 0 0 0", "5\n-5 -3 5 3 0"] | 1 second | ["2", "4", "13"] | NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin. | Java 8 | standard input | [
"dp",
"implementation"
] | 3b3b2408609082fa5c3a0d55bb65d29a | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β the numbers. | 900 | Output a single numberΒ β the minimal number of coins you need to pay to make the product equal to $$$1$$$. | standard output | |
PASSED | af518b5230409e779a080b879bd34a60 | train_003.jsonl | 1566135900 | You are given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \cdot a_2$$$ $$$\dots$$$ $$$\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\cdot (-1) \cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that? | 256 megabytes | import java.util.*;
public class MakeProductEqualOne {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextLong();
}
long a = 0;
for(int i=0;i<n;i++) {
if(arr[i]==0) {
a++;
}
}
long x = 0;
long sum = 0;
for(int i=0;i<n;i++) {
if(arr[i]<0) {
x++;
}
}
Arrays.sort(arr);
for(int i=0;i<n;i++) {
if(arr[i]<-1) {
sum+=(-1-arr[i]);
}
else if(arr[i]>1) {
sum+=(arr[i]-1);
}
else if(arr[i]==0) {
sum+=1;
}
}
if(a==0 && x%2!=0) {
sum+=2;
}
System.out.println(sum);
}
}
| Java | ["2\n-1 1", "4\n0 0 0 0", "5\n-5 -3 5 3 0"] | 1 second | ["2", "4", "13"] | NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin. | Java 8 | standard input | [
"dp",
"implementation"
] | 3b3b2408609082fa5c3a0d55bb65d29a | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β the numbers. | 900 | Output a single numberΒ β the minimal number of coins you need to pay to make the product equal to $$$1$$$. | standard output | |
PASSED | fd67f498f7812b1538ec038d8571fe52 | train_003.jsonl | 1566135900 | You are given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \cdot a_2$$$ $$$\dots$$$ $$$\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\cdot (-1) \cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that? | 256 megabytes | /*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0;i < n; i++){
a[i] = sc.nextInt();
}
ArrayList<Integer> neg = new ArrayList<Integer>();
ArrayList<Integer> pos = new ArrayList<Integer>();
int count = 0;
for(int i = 0; i < n; i++){
if(a[i] < 0)
neg.add(a[i]);
else if(a[i] > 0)
pos.add(a[i]);
else
count++;
}
long res=0;
for(int i = 0; i < neg.size(); i++){
int x = neg.get(i);
if(x != -1){
res += (long)Math.abs(x) - 1;
}
}
//System.out.println("count of 0 "+count);
// System.out.println(neg.size());
if(neg.size() % 2 != 0){
if(count > 0)
{
// System.out.println("hello im in");
count--;
res++;
}
else
res+=2;
}
// System.out.println("count of 0 "+count);
for(int i = 0 ;i < pos.size() ;i++)
{
int x = pos.get(i);
res += (long)x-1;
}
res+=count;
System.out.println(res);
}
} | Java | ["2\n-1 1", "4\n0 0 0 0", "5\n-5 -3 5 3 0"] | 1 second | ["2", "4", "13"] | NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin. | Java 8 | standard input | [
"dp",
"implementation"
] | 3b3b2408609082fa5c3a0d55bb65d29a | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β the numbers. | 900 | Output a single numberΒ β the minimal number of coins you need to pay to make the product equal to $$$1$$$. | standard output | |
PASSED | 5162cd903fd4c83765adcf40ee3de5ff | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
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 Tmbao
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
int inf = (int) 1e9 + 10;
int n, s, l;
int[] a;
int[] itMin, itMax, itF;
int[] id;
void buildIT(int i, int l, int r) {
itF[i] = n + 1;
if (l == r) {
itMin[i] = itMax[i] = a[l];
id[l] = i;
return;
}
int mid = (l + r) / 2;
buildIT(i * 2, l, mid);
buildIT(i * 2 + 1, mid + 1, r);
itMin[i] = Math.min(itMin[i * 2], itMin[i * 2 + 1]);
itMax[i] = Math.max(itMax[i * 2], itMax[i * 2 + 1]);
}
int getMax(int i, int l, int r, int u, int v) {
if (r < u || v < l) return -inf;
if (u <= l && r <= v) return itMax[i];
int mid = (l + r) / 2;
return Math.max(getMax(i * 2, l, mid, u, v), getMax(i * 2 + 1, mid + 1, r, u, v));
}
int getMin(int i, int l, int r, int u, int v) {
if (r < u || v < l) return inf;
if (u <= l && r <= v) return itMin[i];
int mid = (l + r) / 2;
return Math.min(getMin(i * 2, l, mid, u, v), getMin(i * 2 + 1, mid + 1, r, u, v));
}
void updateF(int i, int v) {
i = id[i];
itF[i] = v;
for (i /= 2; i >= 1; i /= 2)
itF[i] = Math.min(itF[i * 2], itF[i * 2 + 1]);
}
int getF(int i, int l, int r, int u, int v) {
if (r < u || v < l) return inf;
if (u <= l && r <= v) return itF[i];
int mid = (l + r) / 2;
return Math.min(getF(i * 2, l, mid, u, v), getF(i * 2 + 1, mid + 1, r, u, v));
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
s = in.nextInt();
l = in.nextInt();
a = new int[n + 10];
for (int i = 1; i <= n; i++)
a[i] = in.nextInt();
itMin = new int[n * 4];
itMax = new int[n * 4];
itF = new int[n * 4];
id = new int[n + 10];
buildIT(1, 0, n);
updateF(0, 0);
for (int i = l, j = 1; i <= n; i++) {
while (getMax(1, 0, n, j, i) - getMin(1, 0, n, j, i) > s) j++;
if (j <= i - l + 1) {
int fCur = getF(1, 0, n, j - 1, i - l) + 1;
updateF(i, fCur);
// out.println(i + " " + j + " " + fCur);
}
}
int ans = getF(1, 0, n, n, n);
if (ans > n) ans = -1;
out.println(ans);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | cadf13c11d6ff5721ef7c31d6c69d4ac | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.*;
public class Main {
static int[][] min, max;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int s = scanner.nextInt();
int l = scanner.nextInt();
int mp = (int) Math.ceil(Math.log(n) / Math.log(2)) + 1;
min = new int[mp][n];
max = new int[mp][n];
for (int i = 0; i < n; i++) {
min[0][i] = scanner.nextInt();
max[0][i] = min[0][i];
}
for (int i = 1; 1 << i <= n; i++) {
for (int j = 0; j < n - (1 << i) + 1; j++) {
min[i][j] = Math.min(min[i - 1][j],
min[i - 1][j + (1 << i - 1)]);
max[i][j] = Math.max(max[i - 1][j],
max[i - 1][j + (1 << i - 1)]);
}
}
int[] dp = new int[n + 1];
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
for (int i = 1; i < n + 1; i++) {
if (i >= l) {
while (!ad.isEmpty() && dp[ad.peekLast()] >= dp[i - l]) {
ad.pollLast();
}
ad.addLast(i - l);
}
while (!ad.isEmpty() && q(ad.peekFirst(), i - 1) > s) {
ad.pollFirst();
}
dp[i] = ad.isEmpty() ? Integer.MAX_VALUE >> 1
: dp[ad.peekFirst()] + 1;
}
System.out.println(dp[n] < Integer.MAX_VALUE >> 2 ? dp[n] : -1);
scanner.close();
}
public static int q(int l, int r) {
int mp = (int) Math.floor(Math.log(r - l + 1) / Math.log(2));
int a = Math.min(min[mp][l], min[mp][r - (1 << mp) + 1]);
int b = Math.max(max[mp][l], max[mp][r - (1 << mp) + 1]);
return b - a;
}
} | Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 2375a6e4c1308d1f24d011897139944e | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws IOException {
new Task().solve();
}
PrintWriter out;
int cnt = 0;
int n;
boolean[] used;
int[] use;
ArrayList<Integer>[] rg;
ArrayList<Integer> tsort = new ArrayList<Integer>();
int[] comp;
int[] compsize;
int[] mt;
int[] a;
int k;
boolean[][] g;
int dp[];
int m;
int[] list;
void solve() throws IOException{
Reader in = new Reader("output.txt");
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//out = new PrintWriter(new FileWriter(new File("output.txt")));
int n = in.nextInt();
int s = in.nextInt();
int l = in.nextInt();
int[] a = new int[n+1];
int[] g = new int[n+1];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Deque<Pair> deq_min = new LinkedList<Pair>();
Deque<Pair> deq_max = new LinkedList<Pair>();
int[] f = new int[n];
int inf = Integer.MAX_VALUE;
int w = 0;
int pos = 0;
for (int i = 0; i < n; i++) {
Pair p = new Pair(a[i], i);
while (!deq_min.isEmpty() && a[i] < deq_min.getLast().v)
deq_min.removeLast();
deq_min.addLast(p);
while (!deq_max.isEmpty() && a[i] > deq_max.getLast().v)
deq_max.removeLast();
deq_max.addLast(p);
w++;
while (deq_max.getFirst().v-deq_min.getFirst().v > s) {
pos++;
while (deq_max.getFirst().i < pos)
deq_max.removeFirst();
while (deq_min.getFirst().i < pos)
deq_min.removeFirst();
}
g[i] = i-pos+1;
//if (g[i] < l)
//g[i] = inf;
}
//for (int i = 0; i < n; i++)
//out.print(g[i]+" ");
//out.println();
SegmentTree st = new SegmentTree(n);
//st.build(1, g, 0, n-1);
//out.println(st.getmin(4, 4));
Arrays.fill(f, 2000000000);
inf = 2000000000;
if (l-1 < n) {
if (g[l-1] == l)
f[l-1] = 1;
else
f[l-1] = inf;
}
for (int i = 0; i <= Math.min(l-1, n-1); i++) {
st.update(f[i], i, 0, n-1, 1);
}
for (int i = l; i < n; i++) {
if (g[i-1]+1 == g[i])
f[i] = f[i-1];
int min = inf;
if (Math.max(0, i-g[i]) <= i-l)
min = st.getmin(Math.max(0, i-g[i]), i-l);
//for (int j = Math.max(0, i-g[i]); j <= i-l; j++)
//if (f[j] != inf)
//out.println(min+" "+Math.max(0, i-g[i])+" "+(i-l));
if (min != inf)
f[i] = Math.min(f[i], min+1);
st.update(f[i], i, 0, n-1, 1);
}
//for (int i = 0; i < n; i++)
//System.out.print(f[i]+" ");
if (f[n-1] == 2000000000)
f[n-1] = -1;
out.print(f[n-1]);
out.flush();
out.close();
}
class SegmentTree {
int n;
int[] t;
int inf = 2_000_000_000;
SegmentTree(int n) {
this.n = n;
t = new int[4*n];
Arrays.fill(t, inf);
}
int getmin(int l, int r) {
//System.out.println(l+" "+r);
return get(l, r, 0, n-1, 1);
}
int get(int l, int r, int tl, int tr, int v) {
//System.out.println(tl+" "+tr+" "+v);
if (l > r)
return inf;
if (tl == l && tr == r)
return t[v];
int tm = (tl+tr)/2;
return Math.min(get(l, Math.min(tm, r), tl, tm, v*2), get(Math.max(tm+1, l), r, tm+1, tr, v*2+1));
}
void build(int v, int[] a, int tl, int tr) {
if (tl == tr) {
t[v] = a[tl];
return;
}
int tm = (tl+tr)/2;
build(v*2, a, tl, tm);
build(v*2+1, a, tm+1, tr);
t[v] = Math.min(t[v*2], t[v*2+1]);
}
void update(int val, int ind, int tl, int tr, int v) {
if (tl == tr) {
t[v] = val;
return;
}
int tm = (tl+tr)/2;
if (ind <= tm)
update(val, ind, tl, tm, v*2);
else
update(val, ind, tm+1, tr, v*2+1);
t[v] = Math.min(t[v*2], t[v*2+1]);
}
}
long pow(int x, int m) {
if (m == 0)
return 1;
return x*pow(x, m-1);
}
}
class Pair implements Comparable<Pair> {
int v;
int i;
Pair (int v, int i) {
this.v = v;
this.i = i;
}
@Override
public int compareTo(Pair p) {
if (v > p.v)
return 1;
if (v < p.v)
return -1;
return 0;
}
}
class Item implements Comparable<Item> {
int v;
int l;
int z;
Item(int v, int l, int z) {
this.v = v;
this.l = l;
this.z = z;
}
@Override
public int compareTo(Item item) {
if (l > item.l)
return 1;
else
if (l < item.l)
return -1;
else {
if (z > item.z)
return 1;
else
if (z < item.z)
return -1;
return 0;
}
}
}
class Reader {
StringTokenizer token;
BufferedReader in;
public Reader(String file) throws IOException {
//in = new BufferedReader( new FileReader( file ) );
in = new BufferedReader( new InputStreamReader( System.in ) );
}
public byte nextByte() throws IOException {
return Byte.parseByte(Next());
}
public int nextInt() throws IOException {
return Integer.parseInt(Next());
}
public long nextLong() throws IOException {
return Long.parseLong(Next());
}
public String nextString() throws IOException {
return in.readLine();
}
public String Next() throws IOException {
while (token == null || !token.hasMoreTokens()) {
token = new StringTokenizer(in.readLine());
}
return token.nextToken();
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | c166935f93205c211b87833ae435aabd | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author about@manhquynh.net
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
int n, s, l, MinValue, MaxValue;
int[] a;
int[] optimize;
Node[] IntervalTree;
class Node<A, B> {
int A;
int B;
Node(int A, int B) {
this.A = A;
this.B = B;
}
}
void buildIntervalTree(int node, int left, int right) {
if (left == right) {
IntervalTree[node].A = a[left];
IntervalTree[node].B = a[left];
return;
}
int mid = (left + right) >> 1;
buildIntervalTree(node * 2, left, mid);
buildIntervalTree(node * 2 + 1, mid + 1, right);
IntervalTree[node].A = Math.max(IntervalTree[node * 2].A, IntervalTree[node * 2 + 1].A);
IntervalTree[node].B = Math.min(IntervalTree[node * 2].B, IntervalTree[node * 2 + 1].B);
}
void QueryIntervalTree(int node, int left, int right, int realleft, int realright) {
if (realleft > right || realright < left)
return;
if (realleft <= left && right <= realright) {
MaxValue = Math.max(MaxValue, IntervalTree[node].A);
MinValue = Math.min(MinValue, IntervalTree[node].B);
return;
}
int mid = (left + right) >> 1;
QueryIntervalTree(node * 2, left, mid, realleft, realright);
QueryIntervalTree(node * 2 + 1, mid + 1, right, realleft, realright);
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
n = in.nextInt();
s = in.nextInt();
l = in.nextInt();
a = new int[n + 1];
optimize = new int[n + 1];
IntervalTree = new Node[n * 4 + 1];
for (int i = 1; i <= n * 4; ++i)
IntervalTree[i] = new Node(0, 0);
for (int i = 1; i <= n; ++i)
a[i] = in.nextInt();
buildIntervalTree(1, 1, n);
int dequeue[] = new int[n + 1];
int head = 1;
int tail = 0;
for (int i = l; i <= n; ++i) {
int left = 1;
int right = i - l + 1;
int front = -1;
while (left <= right) {
int mid = (left + right) >> 1;
MaxValue = -2000000000;
MinValue = 2000000000;
QueryIntervalTree(1, 1, n, mid, i);
if (Math.abs(MaxValue - MinValue) <= s) {
front = mid;
right = mid - 1;
} else
left = mid + 1;
}
// out.println( (front - 1) + " " + (i - l));
if (front == -1)
continue;
--front;
if (i == l ||optimize[i - l] != 0) {
while (tail >= head && optimize[dequeue[tail]] >= optimize[i - l])
--tail;
dequeue[++tail] = i - l;
}
// out.print("E ");
while (tail >= head && dequeue[head] < front)
++head;
// for (int j = head; j <= tail; ++j)
// out.print(dequeue[j] + " ");
// out.println();
if (head <= tail)
optimize[i] = optimize[dequeue[head]] + 1;
}
if (optimize[n] == 0)
out.println(-1);
else
out.println(optimize[n]);
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | a35236753a63da9b2ad83e721dd8b724 | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.awt.print.Book;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.math.BigInteger;
import java.nio.file.attribute.AclEntry.Builder;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.print.CancelablePrintJob;
import javax.swing.text.DefaultEditorKit.InsertBreakAction;
public class A {
final static int MAX = 1000000000;
final static int MOD = 1000000007;
static int arr[];
static int min_sgTree[];
static int max_sgTree[];
static int min_dp[];
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new StringTokenizer("");
min_sgTree = new int[262144];
max_sgTree = new int[262144];
min_dp = new int[262144];
Arrays.fill(min_dp, MAX + 2);
Arrays.fill(min_sgTree, MAX + 2);
Arrays.fill(max_sgTree, -MAX - 2);
int n, s, l;
n = nxtInt();
s = nxtInt();
l = nxtInt();
arr = nxtIntArr(n);
if (l > n) {
out.print(-1);
br.close();
out.close();
return;
}
if (n == 1) {
out.print(l == 1 ? 1 : -1);
br.close();
out.close();
return;
}
int dp[] = new int[n];
int First[] = new int[n];
Arrays.fill(dp, MAX + 2);
Arrays.fill(First, MAX + 2);
build(1, 0, n - 1);
int l1 = 0, r = l - 1;
while (r < n) {
int Max = getMax(1, 0, n - 1, l1, r);
int Min = getMin(1, 0, n - 1, l1, r);
if (r - l1 + 1 < l) {
r++;
continue;
}
if (Max - Min <= s) {
First[r] = l1;
r++;
} else
l1++;
}
// for (int i = 0; i < First.length; i++) {
// System.out.print(First[i] + " ");
// }
// System.out.println();
for (int i = 0; i < l - 1; i++)
Insert(1, 0, n - 1, i, i, dp[i]);
for (int i = l - 1; i < n; i++) {
if (First[i] - 1 >= 0 && i - l >= 0 && i - First[i] + 1 >= l) {
int c = getMinDp(1, 0, n - 1, First[i] - 1, i - l);
dp[i] = c == MAX + 2 ? c : c + 1;
Insert(1, 0, n - 1, i, i, dp[i]);
} else if (First[i] == 0) {
dp[i] = 1;
Insert(1, 0, n - 1, i, i, dp[i]);
}
}
out.print(dp[n - 1] == MAX + 2 ? -1 : dp[n - 1]);
br.close();
out.close();
}
private static int getMinDp(int node, int l, int r, int i, int j) {
if (l >= i && r <= j)
return min_dp[node];
if (i > (l + r) / 2)
return getMinDp(node * 2 + 1, (l + r) / 2 + 1, r, i, j);
else if (j <= (l + r) / 2)
return getMinDp(node * 2, l, (l + r) / 2, i, j);
else {
return Math.min(getMinDp(node * 2, l, (l + r) / 2, i, j),
getMinDp(node * 2 + 1, (l + r) / 2 + 1, r, i, j));
}
}
private static void Insert(int node, int l, int r, int i, int j, int value) {
if (l >= i && r <= j) {
min_dp[node] = value;
return;
}
if (i > (l + r) / 2)
Insert(node * 2 + 1, (l + r) / 2 + 1, r, i, j, value);
else
Insert(node * 2, l, (l + r) / 2, i, j, value);
min_dp[node] = Math.min(min_dp[node * 2], min_dp[node * 2 + 1]);
}
private static void build(int node, int l, int r) {
if (l == r) {
min_sgTree[node] = arr[l];
max_sgTree[node] = arr[l];
return;
}
build(node * 2, l, (l + r) / 2);
build(node * 2 + 1, (l + r) / 2 + 1, r);
min_sgTree[node] = Math.min(min_sgTree[node * 2],
min_sgTree[node * 2 + 1]);
max_sgTree[node] = Math.max(max_sgTree[node * 2],
max_sgTree[node * 2 + 1]);
}
private static int getMin(int node, int l, int r, int i, int j) {
// TODO Auto-generated method stub
if (l >= i && r <= j)
return min_sgTree[node];
if (i > (l + r) / 2)
return getMin(node * 2 + 1, (l + r) / 2 + 1, r, i, j);
else if (j <= (l + r) / 2)
return getMin(node * 2, l, (l + r) / 2, i, j);
else {
return Math.min(getMin(node * 2, l, (l + r) / 2, i, j),
getMin(node * 2 + 1, (l + r) / 2 + 1, r, i, j));
}
}
private static int getMax(int node, int l, int r, int i, int j) {
if (l >= i && r <= j)
return max_sgTree[node];
if (i > (l + r) / 2)
return getMax(node * 2 + 1, (l + r) / 2 + 1, r, i, j);
else if (j <= (l + r) / 2)
return getMax(node * 2, l, (l + r) / 2, i, j);
else {
return Math.max(getMax(node * 2, l, (l + r) / 2, i, j),
getMax(node * 2 + 1, (l + r) / 2 + 1, r, i, j));
}
}
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 BufferedReader br;
static StringTokenizer sc;
static PrintWriter out;
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 | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 9d58558433f2c1512e48b585c387836d | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
public static PrintStream out = System.out;
public static InputReader in = new InputReader(System.in);
public static void main(String args[]) {
int N, S, L;
N = in.nextInt();
S = in.nextInt();
L = in.nextInt();
int[] a = new int[N];
SegmentTree min = new SegmentTree(N);
SegmentTree max = new SegmentTree(N);
SegmentTree dpTree = new SegmentTree(N + 1);
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
min.put(i, a[i]);
max.put(i, -a[i]);
}
int r = N - 1;
dpTree.put(N, 0);
// out.println(dpTree.get(7, 7));
for (int i = N - 1; i >= 0; i--) {
// check i ~ i + L - 1 is good
while (true) {
// out.println(i + " " + (i + L - 1) + " " + Arrays.toString(minMax));
if (-max.get(i, r) - min.get(i, r) > S) {
r--;
} else {
break;
}
}
// out.println(i + " " + r);
if (r - i + 1 >= L) { // i ~ r. i ~ r - L + 1. i + L ~ r + 1
dpTree.put(i, dpTree.get(i + L, r + 1) + 1);
}
}
int ret = dpTree.get(0, 0);
if (ret >= SegmentTree.EMPTY) out.println(-1);
else out.println(ret);
}
static class SegmentTree {
static int EMPTY = (int) 1e9 + 7; // MINIMUM RANGE QUERY so use MAX_VALUE for garbage
int[] ans;
int[] vals;
int size;
SegmentTree(int[] vals) {
this.vals = vals;
this.size = vals.length - 1;
ans = new int[size * 4 + 10];
build(0, 0, size - 1);
}
SegmentTree(int size) {
this.vals = null;
this.size = size;
ans = new int[size * 4 + 10];
Arrays.fill(ans, EMPTY);
}
int unite(int val1, int val2) {
return Math.min(val1, val2);
}
void build(int v, int l, int r) { // O(N)
if (l == r) {
ans[v] = vals[l];
} else {
int m = (l + r) / 2;
build(v * 2 + 1, l, m);
build(v * 2 + 2, m + 1, r);
ans[v] = unite(ans[v * 2 + 1], ans[v * 2 + 2]);
}
}
int get(int needL, int needR) {
return get(0, 0, size - 1, needL, needR);
}
int get(int v, int l, int r, int needL, int needR) { // O(log N)
if (needL > r || needR < l) {
return EMPTY;
}
if (needL <= l && needR >= r) {
return ans[v];
}
int mid = (l + r) / 2;
return unite(get(v * 2 + 1, l, mid, needL, needR),
get(v * 2 + 2, mid + 1, r, needL, needR));
}
void put(int i, int tl, int tr, int pos, int val) { // O(log N)
if (tl == tr) {
ans[i] = val;
return;
}
int m = (tl + tr) / 2;
if (pos <= m)
put(2 * i + 1, tl, m, pos, val);
else
put(2 * i + 2, m + 1, tr, pos, val);
ans[i] = unite(ans[2 * i + 1], ans[2 * i + 2]);
}
void put(int pos, int val) {
put(0, 0, size - 1, pos, val);
}
}
}
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 double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 045f09429b802b9de450efdcd09be2b7 | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;
public class B {
final int oo = (int)1e9;
class IT {
int[] low, high;
int[] min, max;
IT(int N) {
low = new int[4*N+4];
high = new int[4*N+4];
min = new int[4*N+4];
max = new int[4*N+4];
init(1, 0, N-1);
}
private void init(int i, int l, int h) {
low[i] = l;
high[i] = h;
min[i] = oo;
max[i] = -oo;
if (l<h) {
int mid = (h-l)/2+l;
init(i*2, l, mid);
init(i*2+1, mid+1, h);
}
}
int getMin(int l, int h) {
return getMin(1, l, h);
}
private int getMax(int i, int l, int h) {
if (l > high[i] || h < low[i])
return -oo;
if (l <= low[i] && h >= high[i])
return max[i];
return Math.max(getMax(i*2, l, h), getMax(i*2+1, l, h));
}
int getMax(int l, int h) {
return getMax(1, l, h);
}
private int getMin(int i, int l, int h) {
if (l > high[i] || h < low[i])
return oo;
if (l <= low[i] && h >= high[i])
return min[i];
return Math.min(getMin(i*2, l, h), getMin(i*2+1, l, h));
}
private void set(int i, int p, int val) {
if (low[i] > p || high[i] < p)
return;
if (low[i] == high[i]) {
min[i] = val;
max[i] = val;
} else {
set(i*2, p, val);
set(i*2+1, p, val);
min[i] = Math.min(min[i*2], min[i*2+1]);
max[i] = Math.max(max[i*2], max[i*2+1]);
}
}
void set(int p, int val) {
set(1, p, val);
}
}
class MinMaxQueue {
Deque<Integer> q = new ArrayDeque<Integer>();
Deque<Integer> min = new ArrayDeque<Integer>();
Deque<Integer> max = new ArrayDeque<Integer>();
void offer(int val) {
q.offer(val);
while(!min.isEmpty() && min.peekLast() > val)
min.pollLast();
min.offer(val);
while(!max.isEmpty() && max.peekLast() < val)
max.pollLast();
max.offer(val);
}
int poll() {
int ret = q.poll();
if (min.peek() == ret)
min.poll();
if (max.peek() == ret)
max.poll();
return ret;
}
int getMin() {
if (min.isEmpty())
return oo;
return min.peek();
}
int getMax() {
if (max.isEmpty())
return -oo;
return max.peek();
}
}
B(Scanner in) {
int N = in.nextInt();
int S = in.nextInt();
int L = in.nextInt();
IT valsIT = new IT(N);
int[] vals = new int[N];
for (int i=0; i<N; i++) {
vals[i] = in.nextInt();
valsIT.set(i, vals[i]);
}
IT ans = new IT(N+1);
ans.set(0, 0);
MinMaxQueue q = new MinMaxQueue();
int min = 0;
for (int i=0; i<N; i++) {
q.offer(vals[i]);
while(q.getMax() - q.getMin() > S) {
min++;
q.poll();
}
int curAns = ans.getMin(min, i-L+1)+1;
ans.set(i+1, curAns);
// System.out.println(max + " " + i + " " + curAns);
}
int fans = ans.getMin(N, N);
if (fans >= oo)
fans = -1;
System.out.println(fans);
}
public static void main(String[] args) {
new B(new Scanner(System.in));
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 2eff1fd112d18bca37e8ba4b902fe89c | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.NavigableSet;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.Set;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - vuondenthanhcong11@gmail.com
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int maxDelta = in.readInt();
int minLength = in.readInt();
final int[] A = IOUtils.readIntArray(in, count);
IntervalTree minTree = new LongIntervalTree(count + 1) {
protected long joinValue(long left, long right) {
return Math.min(left, right);
}
protected long joinDelta(long was, long delta) {
return Math.min(was, delta);
}
protected long accumulate(long value, long delta, int length) {
return Math.min(value, delta);
}
protected long neutralValue() {
return Integer.MAX_VALUE / 2;
}
protected long neutralDelta() {
return Integer.MAX_VALUE / 2;
}
};
NavigableSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (A[o1] != A[o2])
return A[o1] - A[o2];
return o1 - o2;
}
});
minTree.update(0, 0, 0);
int i = 0;
int start = 0;
while (i < count) {
set.add(i);
while (!set.isEmpty() && A[set.last()] - A[set.first()] > maxDelta)
set.remove(start++);
if (i - start + 1 >= minLength)
minTree.update(i + 1, i + 1, minTree.query(start, i - minLength + 1) + 1);
i++;
}
if (minTree.query(count, count) >= Integer.MAX_VALUE / 2)
out.printLine(-1);
else
out.printLine(minTree.query(count, count));
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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 printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
abstract class IntervalTree {
protected int size;
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from, int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right, int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from, int to);
protected abstract long emptySegmentResult();
public void init() {
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to, long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle, leftResult, rightResult);
}
}
abstract class LongIntervalTree extends IntervalTree {
protected long[] value;
protected long[] delta;
protected LongIntervalTree(int size) {
this(size, true);
}
public LongIntervalTree(int size, boolean shouldInit) {
super(size, shouldInit);
}
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
delta = new long[nodeCount];
}
protected abstract long joinValue(long left, long right);
protected abstract long joinDelta(long was, long delta);
protected abstract long accumulate(long value, long delta, int length);
protected abstract long neutralValue();
protected abstract long neutralDelta();
protected long initValue(int index) {
return neutralValue();
}
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
delta[root] = neutralDelta();
}
protected void initBefore(int root, int left, int right, int middle) {
}
protected void initLeaf(int root, int index) {
value[root] = initValue(index);
delta[root] = neutralDelta();
}
protected void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
protected void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle) {
pushDown(root, left, middle, right);
}
protected void pushDown(int root, int left, int middle, int right) {
value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root], middle - left + 1);
value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root], right - middle);
delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]);
delta[root] = neutralDelta();
}
protected void updateFull(int root, int left, int right, int from, int to, long delta) {
value[root] = accumulate(value[root], delta, right - left + 1);
this.delta[root] = joinDelta(this.delta[root], delta);
}
protected long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
protected void queryPreProcess(int root, int left, int right, int from, int to, int middle) {
pushDown(root, left, middle, right);
}
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
protected long emptySegmentResult() {
return neutralValue();
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 2ee60b6492d7efd092508bba480bcee5 | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.*;
import java.io.*;
public class B
{
public static final int INF = 100000000;
public static void main(String[] args) throws Exception
{
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int s = in.nextInt();
int l = in.nextInt();
IntervalTree it = new IntervalTree(n + 1);
it.inc(0, 0, 0);
ArrayList<Integer> low = new ArrayList<Integer>();
ArrayList<Integer> lowIndex = new ArrayList<Integer>();
ArrayList<Integer> high = new ArrayList<Integer>();
ArrayList<Integer> highIndex = new ArrayList<Integer>();
low.add(Integer.MIN_VALUE);
lowIndex.add(0);
high.add(Integer.MAX_VALUE);
highIndex.add(0);
Compare compare = new Compare();
int left = 0;
for(int x = 1; x <= n; x++)
{
int val = in.nextInt();
int index = Collections.binarySearch(low, val - s);
if(index < 0)
{
index = -(index + 1);
}
index--;
left = Math.max(left, lowIndex.get(index));
index = Collections.binarySearch(high, val + s, compare);
if(index < 0)
{
index = -(index + 1);
}
index--;
left = Math.max(left, highIndex.get(index));
if(left > x - l)
{
it.inc(x, x, INF);
}
else
{
it.inc(x, x, it.query(left, x - l) + 1);
}
while(low.get(low.size() - 1) >= val)
{
low.remove(low.size() - 1);
lowIndex.remove(lowIndex.size() - 1);
}
low.add(val);
lowIndex.add(x);
while(high.get(high.size() - 1) <= val)
{
high.remove(high.size() - 1);
highIndex.remove(highIndex.size() - 1);
}
high.add(val);
highIndex.add(x);
}
int result = it.query(n, n);
if(result >= INF)
{
System.out.println(-1);
}
else
{
System.out.println(result);
}
}
static class IntervalTree
{
public static final int INFINITY = 1000000000;
int n;
int[] tree;
int[] delta;
public IntervalTree(int n)
{
this.n = n;
tree = new int[4 * n];
delta = new int[4 * n];
}
public void inc(int left, int right, int x)
{
inc(left, right, x, 1, 0, n - 1);
}
public void inc(int left, int right, int x, int i, int l, int r)
{
if(r < left || l > right)
{
return;
}
else if(l >= left && r <= right)
{
delta[i] += x;
return;
}
else
{
prop(i);
int m = (l + r) / 2;
inc(left, right, x, 2 * i, l, m);
inc(left, right, x, 2 * i + 1, m + 1, r);
update(i);
}
}
public int query(int left, int right)
{
return query(left, right, 1, 0, n - 1);
}
public int query(int left, int right, int i, int l, int r)
{
if(r < left || l > right)
{
return INFINITY;
}
else if(l >= left && r <= right)
{
return tree[i] + delta[i];
}
else
{
prop(i);
int m = (l + r) / 2;
int ret = Math.min(query(left, right, 2 * i, l, m), query(left, right, 2 * i + 1, m + 1, r));
update(i);
return ret;
}
}
public void prop(int i)
{
delta[2 * i] += delta[i];
delta[2 * i + 1] += delta[i];
delta[i] = 0;
}
public void update(int i)
{
tree[i] = Math.min(tree[2 * i] + delta[2 * i], tree[2 * i + 1] + delta[2 * i + 1]);
}
}
static class Compare implements Comparator<Integer>
{
public int compare(Integer o1, Integer o2)
{
if((int)o2 > (int)o1)
{
return 1;
}
else if((int)o2 < (int)o1)
{
return -1;
}
else
{
return 0;
}
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream input)
{
br = new BufferedReader(new InputStreamReader(input));
st = new StringTokenizer("");
}
public String next() throws IOException
{
if(st.hasMoreTokens())
{
return st.nextToken();
}
else
{
st = new StringTokenizer(br.readLine());
return next();
}
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | d9310f06dc24121ed3258319e8167433 | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.io.*;
import java.util.*;
public class BMain {
String noResultMessage = "NoResult";
Parser in = new Parser();
PrintWriter out;
int n = in.nextInteger();
int s = in.nextInteger();
int l = in.nextInteger();
int[] as = in.nextIntegers(n);
public void solve() {
if(l > n)noResult("-1");
int[] ends = calcEnds();
if(ends[0] == n){
noResult("1");
}
int[] p = new int[n];
int curr = l;
while(curr <= ends[0]){
p[curr++] = 1;
}
for(int i = 1; i < n; ++i){
if(p[i] == 0)continue;
curr = Math.max(curr, i + l);
while(curr <= ends[i]){
if(curr == n)noResult("" + (p[i] + 1));
p[curr++] = p[i] + 1;
}
}
out.println("-1");
}
private int[] calcEnds() {
int[] ends = new int[n];
TreeSet<Long> set = new TreeSet<Long>();
int curr = 0;
for(int i = 0; i < n; ++i){
long a = as[i];
set.add(a * n + i);
int first = (int) (set.first() / n);
int last = (int) (set.last() / n);
while(last - first > s){
ends[curr] = i;
a = as[curr];
set.remove(a * n + curr);
++curr;
first = (int) (set.first() / n);
last = (int) (set.last() / n);
}
}
while(curr < n){
ends[curr++] = n;
}
return ends;
}
static public class Parser{
Scanner scanner;
public Parser() {
scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
}
public Parser(String str) {
scanner = new Scanner(str).useLocale(Locale.ENGLISH);
}
long nextLong(){
return scanner.nextLong();
}
int nextInteger(){
return scanner.nextInt();
}
double nextDouble(){
return scanner.nextDouble();
}
String nextLine(){
return scanner.nextLine();
}
String next(){
return scanner.next();
}
int[] nextIntegers(int count){
int[] result = new int[count];
for(int i = 0; i < count; ++i){
result[i] = nextInteger();
}
return result;
}
long[] nextLongs(int count){
long[] result = new long[count];
for(int i = 0; i < count; ++i){
result[i] = nextLong();
}
return result;
}
int[][] nextIntegers(int fields, int count){
int[][] result = new int[fields][count];
for(int c = 0; c < count; ++c){
for(int i = 0; i < fields; ++i){
result[i][c] = nextInteger();
}
}
return result;
}
}
void noResult(){
throw new NoResultException();
}
void noResult(String str){
throw new NoResultException(str);
}
void run(){
try{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
out = new PrintWriter(outStream);
solve();
out.close();
System.out.print(outStream.toString());
} catch (NoResultException exc){
System.out.print(null == exc.response ? noResultMessage : exc.response);
}
}
public static void main(String[] args) {
new BMain().run();
}
public static class NoResultException extends RuntimeException{
private String response;
public NoResultException(String response) {
this.response = response;
}
public NoResultException() {
}
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 3101bb3e16656bb6273ea98120583c7c | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | // package Div2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
public class Sketch {
private static class Segtree {
public int[] nodes;
private void build(int[] nums, int pos, int head, int tail){
if(head == tail){
if(nums[head] != -1) nodes[pos] = head;
else nodes[pos] = -1;
return;
}
int mid = (head+tail)/2;
build(nums, (pos<<1) + 1, head, mid);
build(nums, (pos<<1) + 2, mid+1, tail);
if(nodes[(pos<<1) + 1] != -1) nodes[pos] = nodes[(pos<<1) + 1];
else nodes[pos] = nodes[(pos<<1) + 2];
}
public Segtree(int[] nums){
nodes = new int[nums.length << 2];
build(nums, 0, 0, nums.length-1);
}
public int find(int[] nums, int l, int r, int pos, int head, int tail){
if(tail < l || head > r) return -1;
if(head >= l && tail <= r) return nodes[pos];
int mid = (head+tail)/2;
int ret0 = find(nums, l, r, 2*pos+1, head, mid);
int ret1 = find(nums, l, r, 2*pos+2, mid+1, tail);
if(ret0 != -1) return ret0;
else return ret1;
}
public void update(int[] nums, int idx, int pos, int head, int tail){
if(head == tail && head == idx){
if(nums[idx] != -1) nodes[pos] = idx;
return;
}
if(idx < head || idx > tail) return;
int mid = (head+tail)/2;
if(idx <= mid) update(nums, idx, 2*pos+1, head, mid);
else update(nums, idx, 2*pos+2, mid+1, tail);
int new0 = nodes[2*pos+1]; int new1 = nodes[2*pos+2];
if(new0 != -1) nodes[pos] = new0;
else nodes[pos] = new1;
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt(); int s = input.nextInt(); int l = input.nextInt();
int[] nums = new int[n];
for(int i=0; i<n; i++) nums[i] = input.nextInt();
input.close();
if(l > n){
System.out.println(-1); return;
}
int[][] rmqmax = new int[n][20];
int[][] rmqmin = new int[n][20];
for(int i=0; i<n; i++){
for(int j=0; j<20; j++){
rmqmax[i][j] = Integer.MIN_VALUE;
rmqmin[i][j] = Integer.MAX_VALUE;
}
}
int offset = 1;
for(int i=0; i<n; i++){
rmqmax[i][0] = nums[i];
rmqmin[i][0] = nums[i];
}
for(int i=1; i<20; i++){
for(int j=0; j<n-offset; j++){
rmqmax[j][i] = Math.max(rmqmax[j][i-1], rmqmax[j+offset][i-1]);
rmqmin[j][i] = Math.min(rmqmin[j][i-1], rmqmin[j+offset][i-1]);
}
offset = offset << 1;
}
int[] dps = new int[n];
for(int i=0; i<n; i++) dps[i] = -1;
Segtree seg = new Segtree(dps);
for(int i=l-1; i<n; i++){
int hd = 0; int tl = i-l+1;
boolean flag = false;
do{
boolean quit = hd == tl;
int mid = (hd+tl)/2;
int pow = 1; int idx = 0;
while(pow<<1 <= i-mid){
pow = pow << 1; idx++;
}
int maxi = Math.max(rmqmax[mid][idx], rmqmax[i-pow+1][idx]);
int mini = Math.min(rmqmin[mid][idx], rmqmin[i-pow+1][idx]);
if(maxi-mini <= s){
flag = true;
tl = mid;
}
else hd = mid+1;
if(quit) break;
}while(true);
if(!flag) continue;
if(hd == 0) dps[i] = 1;
else {
int first = seg.find(dps, hd-1, i-l, 0, 0, n-1);
if(first == -1) continue;
dps[i] = dps[first] + 1;
}
seg.update(dps, i, 0, 0, n-1);
}
System.out.println(dps[n-1]);
}
} | Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 720f35f35e1a4fd319db696d5cab2e1c | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.*;
public class Main {
static int[][] min, max;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int s = scanner.nextInt();
int l = scanner.nextInt();
int mp = (int) Math.ceil(Math.log(n) / Math.log(2)) + 1;
min = new int[mp][n];
max = new int[mp][n];
for (int i = 0; i < n; i++) {
min[0][i] = scanner.nextInt();
max[0][i] = min[0][i];
}
for (int i = 1; 1 << i <= n; i++) {
for (int j = 0; j < n - (1 << i) + 1; j++) {
min[i][j] = Math.min(min[i - 1][j],
min[i - 1][j + (1 << i - 1)]);
max[i][j] = Math.max(max[i - 1][j],
max[i - 1][j + (1 << i - 1)]);
}
}
int[] dp = new int[n + 1];
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
for (int i = 1; i < n + 1; i++) {
if (i >= l) {
while (!ad.isEmpty() && dp[ad.peekLast()] >= dp[i - l]) {
ad.pollLast();
}
ad.addLast(i - l);
}
while (!ad.isEmpty() && q(ad.peekFirst(), i - 1) > s) {
ad.pollFirst();
}
dp[i] = ad.isEmpty() ? Integer.MAX_VALUE >> 1
: dp[ad.peekFirst()] + 1;
}
System.out.println(dp[n] < Integer.MAX_VALUE >> 2 ? dp[n] : -1);
scanner.close();
}
public static int q(int l, int r) {
int mp = (int) Math.floor(Math.log(r - l + 1) / Math.log(2));
int a = Math.min(min[mp][l], min[mp][r - (1 << mp) + 1]);
int b = Math.max(max[mp][l], max[mp][r - (1 << mp) + 1]);
return b - a;
}
} | Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 1bb0c0b1b3296aab43b9af5b1dd9ce1b | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class SolverB {
public static void main(String[] Args) throws NumberFormatException,
IOException {
new SolverB().Run();
}
PrintWriter pw;
StringTokenizer Stok;
BufferedReader br;
public String nextToken() throws IOException {
while (Stok == null || !Stok.hasMoreTokens()) {
Stok = new StringTokenizer(br.readLine());
}
return Stok.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
int n;
int minLen, diff;
int[] mas;
int[] resKol;
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
SortedSet<Integer> set=new TreeSet<Integer>();
int getKol(int value){
Integer zn=map.get(value);
if (zn==null)
zn=0;
return zn;
}
void addNum(int value){
Integer zn=map.get(value);
if (zn==null){
set.add(value);
zn=0;
}
zn++;
map.put(value, zn);
}
void removeNum(int value){
Integer zn=map.get(value);
if (zn==null)
return;
if (zn==1){
map.remove(value);
set.remove(value);
return;
}
zn--;
map.put(value, zn);
}
boolean isPossible(){
if (minLen>n)
return false;
Arrays.fill(resKol, -1);
resKol[0]=0;
for (int i=1; i<=minLen; i++){
addNum(mas[i]);
}
int min=set.first();
int max=set.last();
if (max-min>diff)
return false;
resKol[minLen]=1;
int i1=0;
for (int i=minLen+1; i<=n; i++){
addNum(mas[i]);
min=set.first();
max=set.last();
while ((max-min>diff || resKol[i1]<0) && (i1<i)){
i1++;
removeNum(mas[i1]);
if (!set.isEmpty()){
min=set.first();
max=set.last();
}
}
if (i1==i){
return false;
}
if (i-i1>=minLen){
resKol[i]=resKol[i1]+1;
}
}
return true;
}
public void Run() throws NumberFormatException, IOException {
//br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter("output.txt");
br=new BufferedReader(new InputStreamReader(System.in)); pw=new PrintWriter(new OutputStreamWriter(System.out));
n=nextInt();
diff=nextInt();
minLen=nextInt();
resKol=new int[n+1];
mas=new int[n+1];
for (int i=1; i<=n; i++){
mas[i]=nextInt();
}
if (isPossible()){
pw.println(resKol[n]);
} else {
pw.println("-1");
}
pw.flush();
pw.close();
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | 3be8b77903238bca50d582e11beafd2f | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 4 4
* 1 5 3 4
* 1 2
* 1 3
* 2 3
* 3 3
*
*
* @author pttrung
*/
public class A {
public static long Mod = (long) (1e9) + 7;
static int[] dp;
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
long s = in.nextInt();
int l = in.nextInt();
long[] data = new long[n + 1];
for (int i = 1; i <= n; i++) {
data[i] = in.nextInt();
}
int[] g = new int[n + 1];
int[] f = new int[n + 1];
Deque<Integer> min = new LinkedList();
Deque<Integer> max = new LinkedList();
for (int i = 1, k = 1; i <= n; i++) {
while (!min.isEmpty() && data[min.getLast()] >= data[i]) {
min.removeLast();
}
min.addLast(i);
while (!max.isEmpty() && data[max.getLast()] <= data[i]) {
max.removeLast();
}
max.addLast(i);
while (data[max.getFirst()] - data[min.getFirst()] > s) {
if (min.getFirst() == k) {
min.removeFirst();
}
if (max.getFirst() == k) {
max.removeFirst();
}
k++;
}
g[i] = k - 1;
}
// System.out.println(Arrays.toString(g));
min.clear();
int oo = (int) (1e9);
for (int i = 1, k = 0; i <= n; i++) {
for (; k <= i - l; k++) {
if (f[k] == oo) {
continue;
}
while (!min.isEmpty() && f[min.getLast()] >= f[k]) {
min.removeLast();
}
min.addLast(k);
}
while (!min.isEmpty() && min.getFirst() < g[i]) {
min.removeFirst();
}
f[i] = (min.isEmpty() ? oo : f[min.getFirst()] + 1);
}
out.println((f[n] == oo ? -1 : f[n]));
out.close();
}
static class Node implements Comparable<Node> {
int start, end, index;
public Node(int start, int end, int index) {
this.start = start;
this.end = end;
this.index = index;
}
@Override
public int compareTo(Node o) {
int a = end - start;
int b = o.end - o.start;
if (a != b) {
return a - b;
}
return index - o.index;
}
}
static int find(int index, int[] u) {
if (index != u[index]) {
return u[index] = find(u[index], u);
}
return index;
}
public static long pow(int a, int b, long mod) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long v = pow(a, b / 2, mod);
if (b % 2 == 0) {
return (v * v) % mod;
} else {
return (((v * v) % mod) * a) % mod;
}
}
public static int[][] powSquareMatrix(int[][] A, long p) {
int[][] unit = new int[A.length][A.length];
for (int i = 0; i < unit.length; i++) {
unit[i][i] = 1;
}
if (p == 0) {
return unit;
}
int[][] val = powSquareMatrix(A, p / 2);
if (p % 2 == 0) {
return mulMatrix(val, val);
} else {
return mulMatrix(A, mulMatrix(val, val));
}
}
public static int[][] mulMatrix(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
long temp = 0;
for (int k = 0; k < A[0].length; k++) {
temp += ((long) A[i][k] * B[k][j] % Mod);
temp %= Mod;
}
temp %= Mod;
result[i][j] = (int) temp;
}
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return (val * val % Mod) * a % Mod;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
//
// static Point add(Point a, Point b) {
// return new Point(a.x + b.x, a.y + b.y);
// }
//
/**
* Cross product ab*ac
*
* @param a
* @param b
* @param c
* @return
*/
static double cross(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return cross(ab, ac);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
/**
* Dot product ab*ac;
*
* @param a
* @param b
* @param c
* @return
*/
static long dot(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return dot(ab, ac);
}
static long dot(Point a, Point b) {
long total = a.x * b.x;
total += a.y * b.y;
return total;
}
static double dist(Point a, Point b) {
long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(total);
}
static long norm(Point a) {
long result = a.x * a.x;
result += a.y * a.y;
return result;
}
static double dist(Point a, Point b, Point x, boolean isSegment) {
double dist = cross(a, b, x) / dist(a, b);
// System.out.println("DIST " + dist);
if (isSegment) {
Point ab = new Point(b.x - a.x, b.y - a.y);
long dot1 = dot(a, b, x);
long norm = norm(ab);
double u = (double) dot1 / norm;
if (u < 0) {
return dist(a, x);
}
if (u > 1) {
return dist(b, x);
}
}
return Math.abs(dist);
}
static long squareDist(Point a, Point b) {
long x = a.x - b.x;
long y = a.y - b.y;
return x * x + y * y;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader(new File("A-large (2).in")));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output | |
PASSED | e0540a4b6a8df07eddac854c586fd0e1 | train_003.jsonl | 1416590400 | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above. | 256 megabytes | import java.util.*;
public class Main {
static int[][] min, max;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int s = scanner.nextInt();
int l = scanner.nextInt();
int mp = (int) Math.ceil(Math.log(n) / Math.log(2)) + 1;
min = new int[mp][n];
max = new int[mp][n];
for (int i = 0; i < n; i++) {
min[0][i] = scanner.nextInt();
max[0][i] = min[0][i];
}
for (int i = 1; 1 << i <= n; i++) {
for (int j = 0; j < n - (1 << i) + 1; j++) {
min[i][j] = Math.min(min[i - 1][j],
min[i - 1][j + (1 << i - 1)]);
max[i][j] = Math.max(max[i - 1][j],
max[i - 1][j + (1 << i - 1)]);
}
}
int[] dp = new int[n + 1];
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
for (int i = 1; i < n + 1; i++) {
if (i >= l) {
while (!ad.isEmpty() && dp[ad.peekLast()] >= dp[i - l]) {
ad.pollLast();
}
ad.addLast(i - l);
}
while (!ad.isEmpty() && q(ad.peekFirst(), i - 1) > s) {
ad.pollFirst();
}
dp[i] = ad.isEmpty() ? Integer.MAX_VALUE >> 1
: dp[ad.peekFirst()] + 1;
}
System.out.println(dp[n] < Integer.MAX_VALUE >> 2 ? dp[n] : -1);
scanner.close();
}
public static int q(int l, int r) {
int mp = (int) Math.floor(Math.log(r - l + 1) / Math.log(2));
int a = Math.min(min[mp][l], min[mp][r - (1 << mp) + 1]);
int b = Math.max(max[mp][l], max[mp][r - (1 << mp) + 1]);
return b - a;
}
} | Java | ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"] | 1 second | ["3", "-1"] | NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Java 7 | standard input | [
"dp",
"two pointers",
"binary search",
"data structures"
] | 3d670528c82a7d8dcd187b7304d36f96 | The first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105). The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109). | 2,000 | Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.