본문 바로가기
자료구조 & 알고리즘/코딩 테스트

[백준 1700번-그리디] 멀티탭 스케줄링(java)

by 코딩공장공장장 2023. 8. 12.

백준 1700번 - 그리디알고리즘

난이도 : 골드1

더보기
더보기

멀티탭 스케줄링 

 

문제

기숙사에서 살고 있는 준규는 한 개의 멀티탭을 이용하고 있다. 준규는 키보드, 헤어드라이기, 핸드폰 충전기, 디지털 카메라 충전기 등 여러 개의 전기용품을 사용하면서 어쩔 수 없이 각종 전기용품의 플러그를 뺐다 꽂았다 하는 불편함을 겪고 있다. 그래서 준규는 자신의 생활 패턴을 분석하여, 자기가 사용하고 있는 전기용품의 사용순서를 알아내었고, 이를 기반으로 플러그를 빼는 횟수를 최소화하는 방법을 고안하여 보다 쾌적한 생활환경을 만들려고 한다.

예를 들어 3 구(구멍이 세 개 달린) 멀티탭을 쓸 때, 전기용품의 사용 순서가 아래와 같이 주어진다면,

  1. 키보드
  2. 헤어드라이기
  3. 핸드폰 충전기
  4. 디지털 카메라 충전기
  5. 키보드
  6. 헤어드라이기

키보드, 헤어드라이기, 핸드폰 충전기의 플러그를 순서대로 멀티탭에 꽂은 다음 디지털 카메라 충전기 플러그를 꽂기 전에 핸드폰충전기 플러그를 빼는 것이 최적일 것이므로 플러그는 한 번만 빼면 된다.

입력

첫 줄에는 멀티탭 구멍의 개수 N (1 ≤ N ≤ 100)과 전기 용품의 총 사용횟수 K (1 ≤ K ≤ 100)가 정수로 주어진다. 두 번째 줄에는 전기용품의 이름이 K 이하의 자연수로 사용 순서대로 주어진다. 각 줄의 모든 정수 사이는 공백문자로 구분되어 있다.

 

출력

하나씩 플러그를 빼는 최소의 횟수를 출력하시오.

 

예제 입력 1

2 7
2 3 2 3 1 2 7

예제 출력 1

2
 

 

 

 

오답 풀이: 

'N구의 멀티탭에 최초 N개의 디바이스를 모두 플러그인한 후 다음 N개의 디바이스 중 이미 멀티탭에 꼽혀있는 것 제외하고 교체'

 

import java.io.*;
import java.util.*;


public class Main {

	    public static void main(String[] args) throws IOException{
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        String str = br.readLine();
	        String[] strArr = str.split(" ");
	        int holeCnt = Integer.parseInt(strArr[0]);
	        int useCnt = Integer.parseInt(strArr[1]);
	        String[] deviceInfo = br.readLine().split(" ");
	        int[] arr = new int[useCnt];
	        for(int i=0; i<useCnt; i++) arr[i]=Integer.parseInt(deviceInfo[i]);
	        System.out.println(solution(holeCnt, useCnt, arr));
	    }
	    
	    public static int solution(int holeCnt, int useCnt, int[] arr){
	    	TreeSet<Integer> multiTap = new TreeSet<>();
	        TreeSet<Integer> addTarget = new TreeSet<>();
	        
	        //멀티탭에 N구 꽉채우기
	        int k=0;
	        for(int i=0; i<useCnt; i++){
	          if(multiTap.size()==holeCnt){
	              k=i;
	              break;
	          }
	          multiTap.add(arr[i]);
	        }
	        
	        int ans=0;
	        for(int i=k; i<useCnt; i++) {
	            if(addTarget.size()==holeCnt){
	            	String plugOutDevice="";
	            	for(Integer device : multiTap) if(!addTarget.contains(device)) plugOutDevice+=device+",";
	            	//멀티탭코드 뽑기
	                for(String device : plugOutDevice.split(",")) {
	                	if(device.equals("")) continue;
	                	multiTap.remove(Integer.parseInt(device));
	                	ans++;
	                }
	                //addTarget 중 멀티탭에 없는 것 추가 
	                for(int key : addTarget) multiTap.add(key);
	                addTarget.clear();
	            }
	            addTarget.add(arr[i]);
	        }
	        for(Integer device : addTarget) if(!multiTap.contains(device)) ans++;
	        return ans;
	    }
	    
}

 

반례 :

3 8

2 3 4 1 5 2 3 2

 

오답 : 3

정답 : 2

 

오답이유 : 

위 로직에서 만일 2, 3, 4 디바이스가 멀티탭에 꽂혀 있고  그 다음 1, 5, 2가 꽂힐 대상이라면 3, 4가 뽑고 1, 5가 꽂혀

1, 2, 5가 멀티탭에 꽂히고 그 다음 3, 2가 꼽힐 대상이므로 1이나 5 둘 중 하나가 뽑혀 총 3번 뽑아야 된다.

허나 위 케이스는 2, 3, 4에서 4를 뽑고 1을 꼽은 다음 다시 1을 뽑고 5를 꼽는다면 2번만 뽑아도 모든 디바이스를 사용할 수 있다.

따라서 N개 단위로 디바이스를 교체하는 방식은 잘못된 방식이다.

 

정답풀이 :

'멀티탭에 꽂혀 있는 디바이스 중 가장 나중에 사용되는 것부터 교체'

 

시간복잡도 : O(N^2)

import java.io.*;
import java.util.*;


public class Main {

	    public static void main(String[] args) throws IOException{
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        StringTokenizer st = new StringTokenizer(br.readLine());
	        int holeCnt = Integer.parseInt(st.nextToken());
	        int useCnt = Integer.parseInt(st.nextToken());
	        st = new StringTokenizer(br.readLine());
	        int[] arr = new int[useCnt];
	        for(int i=0; i<useCnt; i++) arr[i]=Integer.parseInt(st.nextToken());
	        System.out.println(solution(holeCnt, useCnt, arr));
	    }
	    
	    public static int solution(int holeCnt, int useCnt, int[] arr){
	    	int ans=0;
            
            //각 디바이스별 다음 사용 인덱스 저장
            int[][] lruInfoArr = new int[useCnt][2];
            for(int i=0; i<useCnt; i++){
            	lruInfoArr[i][0]=arr[i];
            	lruInfoArr[i][1]=useCnt;
                for(int j=i+1; j<useCnt; j++){
                    if(arr[i]==arr[j]) {
                       lruInfoArr[i][1]=j;
                       break;
                    }
                }
            }
            
            //멀티탭에 최초 n개 디바이스 플러그인
            ArrayList<DeviceInfo> multiTap = new ArrayList<>();
            int k=0;
            for(int i=0; i<useCnt; i++){
                if(multiTap.size()==holeCnt){
                    k=i;
                    break;
                }
                for(int j=0; j<multiTap.size(); j++) {
                	if(multiTap.get(j).device==arr[i]) {
                		multiTap.remove(j);
                		break;
                	}
                }
                multiTap.add(new DeviceInfo(lruInfoArr[i][0], lruInfoArr[i][1]));
            }
            
            for(int i=k; i<useCnt; i++){
                boolean isPlugged = false;
                for(DeviceInfo device : multiTap){
                    if(device.device==lruInfoArr[i][0]){
                        isPlugged=true;
                        device.nextUseIdx=lruInfoArr[i][1];
                        break;
                    }
                }
                
                //디바이스 멀티탭에 안 꼽혀 있으면 꼽기
                if(!isPlugged){
                    ans++;
                    Collections.sort(multiTap);
                    multiTap.remove(0);
                    multiTap.add(new DeviceInfo(lruInfoArr[i][0], lruInfoArr[i][1]));
                }
            }
            return ans;
	    }
	    
}

class DeviceInfo implements Comparable<DeviceInfo>{
    int device;
    int nextUseIdx;
    
    @Override
    public int compareTo(DeviceInfo info){
        return info.nextUseIdx<this.nextUseIdx?-1:1;
    }
    
    DeviceInfo(int device, int nextUseIdx){
        this.device=device;
        this.nextUseIdx=nextUseIdx;
    }
}

 

정답 풀이2:

같은 알고리즘(표현방식만 다름)

import java.io.*;
import java.util.*;


public class Main {

	    public static void main(String[] args) throws IOException{
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        String str = br.readLine();
	        String[] strArr = str.split(" ");
	        int holeCnt = Integer.parseInt(strArr[0]);
	        int useCnt = Integer.parseInt(strArr[1]);
	        String[] deviceInfo = br.readLine().split(" ");
	        int[] arr = new int[useCnt];
	        for(int i=0; i<useCnt; i++) arr[i]=Integer.parseInt(deviceInfo[i]);
	        System.out.println(solution(holeCnt, useCnt, arr));
	    }
	    
	    public static int solution(int holeCnt, int useCnt, int[] arr){
	    	int ans=0;
            
            //멀티탭에 최초 n개 디바이스 플러그인
            TreeSet<Integer> multiTap = new TreeSet<>();
            int idx=0;
            for(int i=0; i<useCnt; i++){
                if(multiTap.size()==holeCnt){
                    idx=i;
                    break;
                }
                multiTap.add(arr[i]);
            }
            
            for(int i=idx; i<useCnt; i++){
            	if(multiTap.contains(arr[i])) continue;
            	
            	//플러그 아웃 대상 디바이스 찾기
            	int plugOutDevice=0;
            	int plugOutDeviceIdx=0;
                for(Integer device: multiTap) {
                	boolean isChng=false;
                	for(int k=i+1; k<useCnt; k++){
                		if(device==arr[k]) {
                			isChng=true;
                			plugOutDeviceIdx=k>plugOutDeviceIdx?k:plugOutDeviceIdx;
                			plugOutDevice=arr[plugOutDeviceIdx];
                			break;
                		}
                    }
                	if(!isChng) {
                		plugOutDevice= device;
                		break;
                	}
                }
                ans++;
                multiTap.remove(plugOutDevice);
                multiTap.add(arr[i]);
            }
            return ans;
	    }
	    
}
반응형