알고리즘 단련장/해커랭크

[해커랭크] Cut the sticks

snapcoder 2025. 10. 11. 20:38
728x90
반응형
SMALL

[해커랭크] Cut the sticks

 

https://www.hackerrank.com/challenges/cut-the-sticks/problem?isFullScreen=true

 

Cut the sticks | HackerRank

Given the lengths of n sticks, print the number of sticks that are left before each cut operation.

www.hackerrank.com

 

You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.

Given the lengths of  sticks, print the number of sticks that are left before each iteration until there are none left.

Example

The shortest stick length is , so cut that length from the longer two and discard the pieces of length . Now the lengths are . Again, the shortest stick is of length , so cut that amount from the longer stick and discard those pieces. There is only one stick left, , so discard that stick. The number of sticks at each iteration are .

Function Description

Complete the cutTheSticks function in the editor below. It should return an array of integers representing the number of sticks before each cut operation is performed.

cutTheSticks has the following parameter(s):

  • int arr[n]: the lengths of each stick

Returns

  • int[]: the number of sticks after each iteration

Input Format

The first line contains a single integer , the size of .
The next line contains  space-separated integers, each an , where each value represents the length of the  stick.

Constraints

  •  
  •  

Sample Input 0

STDIN           Function
-----           --------
6               arr[] size n = 6
5 4 4 2 2 8     arr = [5, 4, 4, 2, 2, 8]

Sample Output 0

6
4
2
1

Explanation 0

sticks-length        length-of-cut   sticks-cut
5 4 4 2 2 8             2               6
3 2 2 _ _ 6             2               4
1 _ _ _ _ 4             1               2
_ _ _ _ _ 3             3               1
_ _ _ _ _ _           DONE            DONE

Sample Input 1

8
1 2 3 4 3 3 2 1

Sample Output 1

8
6
4
1

Explanation 1

sticks-length         length-of-cut   sticks-cut
1 2 3 4 3 3 2 1         1               8
_ 1 2 3 2 2 1 _         1               6
_ _ 1 2 1 1 _ _         1               4
_ _ _ 1 _ _ _ _         1               1
_ _ _ _ _ _ _ _       DONE            DONE

 

 

 

풀이

오름차순 정렬 후, 가장 작은 첫번째 수에 대해서,

size - (첫번째 수의 개수) 를 정답 리스트에 add 해준다.

 

추가적으로 내가 푼 로직에서는 0이 추가되지 않도록 종료조건을 설정해주었다.

if(arr.size() - (countInList) == 0) break;

 

 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'cutTheSticks' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts INTEGER_ARRAY arr as parameter.
     */

    public static List<Integer> cutTheSticks(List<Integer> arr) {
   
        // Collections.sort(arr,
        //     (a,b) -> a<b ? a-b : b-a
        // );
        // for(int i=0; i<arr.size(); i++){
        //     System.out.println(arr.get(i));
        // }
       
        List<Integer> result = new ArrayList<>();
        result.add(arr.size());
        Collections.sort(arr);  // 3 5 8 8 10 12 14 14
       
        while(arr.size() > 0){
            Integer firstNum = arr.get(0);
            Integer countInList = arr.lastIndexOf(firstNum)+1;
           
            if(arr.size() - (countInList) == 0) break;
            result.add(arr.size() - (countInList));
            // System.out.println(firstNum + ", " + countInList + " / " + arr);
           
            for(int j=0; j<countInList; j++){
                arr.remove(0);
            }
        }
        // System.out.println(result);

        return result;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> result = Result.cutTheSticks(arr);

        bufferedWriter.write(
            result.stream()
                .map(Object::toString)
                .collect(joining("\n"))
            + "\n"
        );

        bufferedReader.close();
        bufferedWriter.close();
    }
}

 

 

 

728x90
반응형
LIST

'알고리즘 단련장 > 해커랭크' 카테고리의 다른 글

[해커랭크] Library Fine  (0) 2025.10.11
[해커랭크] Sherlock and Squares  (0) 2025.10.11
[해커랭크] Append and Delete  (0) 2025.10.11
[해커랭크] Extra Long Factorials  (0) 2025.08.14
[해커랭크] Utopian Tree  (0) 2025.08.14