안녕하세요. 오늘은 큐를 회전시킬거예요.

문제

https://www.acmicpc.net/problem/1021

아이디어

오른쪽으로 일단 돌려봅니다.
그리고 그 값을 cnt라고 할때
min(cnt,큐의크기-cnt)의 합을 구해주면 됩니다.

소스코드

#include <iostream>
#include <algorithm>
#define ll long long
using namespace std;

int main(void)
{
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	ll N, M, i, arr[55] = { 0 }, x, ans = 0, cnt;

	cin >> N >> M;
	ll now = 1;
	for (i = 0; i < M; i++)
	{
		cin >> x;
		cnt = 0;
		while (now != x)
		{
			if (arr[now] == 0) cnt++;
			now++;
			if (now == N + 1) now = 1;
		}
		ans += min(cnt, N - i - cnt);
		arr[x] = 1;

		now++;
		if (now == N + 1) now = 1;
	}

	cout << ans;
}


감사합니다.

0개의 댓글