글 작성자: Doublsb

https://programmers.co.kr/learn/courses/30/lessons/42583

 

풀이

- 정해진 순서로 모든 트럭이 다리를 건너려면 최소 몇 초인가

- 다리에는 최대 트럭 개수와 최대 하중이 있다

- 완전히 오르지 않은 트럭 무게는 무시

 

- int 배열형으로 다리의 상태를 표시하자

- Aging 할 때마다 맨 앞은 DeQueue하고 각 배열 원소를 앞으로 이동한다

- 맨 뒤 배열 원소를 0으로 만든다

- 트럭을 올릴 수 있는지 없는지 판단한 뒤 트럭을 올리자

 

C#

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        
        var waiting = new List<int>(truck_weights);
        var bridge = new Bridge(bridge_length, weight);
        
        int Time = 0;

        while(waiting.Count > 0 || bridge.Current_Weight != 0)
        {
            bridge.Aging();
            if(waiting.Count > 0 && bridge.TryPass(waiting[0])) waiting.RemoveAt(0);
            Time++;          
        }

        return Time;
    }
}

public class Bridge {
    
    private int[] State;

    private int Maximum_Weight;
    public int Current_Weight;

    public Bridge(int length, int weight)
    {
        State = new int[length];
        Maximum_Weight = weight;
        Current_Weight = 0;
    }
    
    public bool isPassable(int weight)
    {
        return Maximum_Weight >= Current_Weight + weight
            && State[State.Length - 1] == 0;
    }
    
    public bool TryPass(int weight)
    {
        if(isPassable(weight))
        {
            State[State.Length - 1] = weight;
            Current_Weight += weight;
            return true;
        }
        else return false;
    }

    public void Aging()
    {
        Current_Weight -= State[0];
        
        for(int i=0; i<State.Length - 1; i++)
        {
            State[i] = State[i+1];
        }
        
        State[State.Length - 1] = 0;
    }
}

 

결과

100.0 / 100.0

 

피드백

처음에는 다리를 List<int>형으로 구현했는데, 다리의 길이와 현재 상태를 측정하는 게 오히려 어려웠음

그래서 배열형으로 구현했더니 더 명확해졌다.

반응형