스터디/알고리즘

[알고리즘][C++] 멀티태스킹

y00&z1 2022. 8. 7. 02:55

공주 구하기 문제와 유사한 문제! (pos 변수 이용)

 

🔽

1 2 3
1 2 3

                          🔽

1 2 3
0 1 3

                                                🔽

1 2 3
0 1 2

                        🔽

1 2 3
0 0 2

                                              🔽

1 2 3
0 0 1
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

int a[2001];
int main(){ 
	//freopen("input.txt", "rt", stdin);
	int n, i, k, cnt=0, pos=0, total=0; 
	
	scanf("%d", &n);
	for(i=1; i<=n; i++){
		scanf("%d", &a[i]);
		total+=a[i]; //정전 전에 전부 처리되었는지를 판단하기 위해서
	}
	scanf("%d", &k);
	
	if(k>=total) { //정전 전에 전부 처리되면 -1 출력
		printf("-1");
		return 0;
	}
	
	while(1){
		pos++;
		if(pos>n) pos=1; //n보다 커지면 다시 처음으로
		
		if(a[pos]==0) continue;
		
		a[pos]--;
		cnt++;
		
		if(cnt==k) break;
	}

//정전 후 시작해야하는 프로그램 알아내기
	while(1){
		pos++;
		if(pos>n) pos=1;
		
		if(a[pos]!=0) break;
	}
	printf("%d", pos);
	
	return 0;
}

//타임리밋+잘못된 정답
//int main(){ 
//	//freopen("input.txt", "rt", stdin);
//	int n, i, k, cnt=0; 
//	
//	scanf("%d", &n);
//	int *x = new int[n+1];
//	for(i=1; i<=n; i++){
//		scanf("%d", &x[i]);
//	}
//	scanf("%d", &k);
//
//	for(i=1; i<=k; i++){
//		for(int j=1; j<=n; j++){
//			if(cnt>=n)	cnt=1;
//
//			if(x[j]>0){
//				x[j]--;
//				cnt++;
//			}
//		}
//	}
//단순하게 정전 전에 다음 작업을 출력한다고 생각했는데 반복문을 돌려서 탐색해서 따로 구해야 한다!
//	printf("%d", cnt+1); 
//	
//	delete[] x;
//	
//	return 0;
//}