반응형

문제 링크

www.acmicpc.net/problem/18322

 

18322번: Word Processor

Including "hello" and "my", the first line contains 7 non-space characters. Adding "name" would cause the first line to contain $11>7$ non-space characters, so it is placed on a new line.

www.acmicpc.net

풀이 및 코드

import java.util.Scanner;

public class Main {

    // USACO Word Processor JAVA
    // 백준 18322

    /**
     * n개의 단어가 주어진다.
     * 한 줄에는 최대 k개의 알파벳이 있을 수 있다.
     *
     * 이 문제를 푸는데 7번이나 실패했다.
     * 문제를 다시 읽어보니 각 라인의 끝에는 공백이 있으면 안되는거였다.
     * 번역기 이후에 꼭 직접 읽어보고 풀도록 하자 ...
     */
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int k = sc.nextInt();
        sc.nextLine();
        String str = sc.nextLine();

        String[] strArr = str.split(" ");

        int cnt = 0;    //현재 라인의 알파벳 갯수
        for (int i = 0; i < n; i++) {
            cnt += strArr[i].length();

            if (!(cnt > k)) {   //현재 라인에 출력
                if(i == 0) System.out.print(strArr[i]);
                else System.out.print(" " + strArr[i]);
            } else {          //다음 라인에 출력
                System.out.print("\n" + strArr[i]);
                cnt = strArr[i].length();
            }
        }

    }//main

}//class


반응형

'개발 > 알고리즘' 카테고리의 다른 글

[USACO] 소가 길을 건너간 이유 3 백준 14469  (0) 2021.02.26
[USACO] Teleportation JAVA  (0) 2021.02.25
[USACO] Just Stalling JAVA  (0) 2021.02.23
[USACO] Mad Scientist JAVA  (0) 2021.02.23
[USACO] Even More Odd Photos JAVA  (0) 2021.02.23
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기