본문 바로가기

알고리즘/SWEA

6808

static int table[2][19];
static int a[9], b[9];
static int ans[2];

static void __solution(int len, int as, int bs)
{
	//재귀에서는 가급전 인자로 받은 변수에 대해서 += 과 같은 연산을 하지 말 것.

	if (len == 9)
	{
		if (as > bs)
			ans[0] += 1;
		else if (as < bs)
			ans[1] += 1;

		return;
	}

	for (int i = 0; i < 9; i++)
	{
		if (!table[1][b[i]])
		{
			int score = a[len] + b[i];

			table[1][b[i]] = 1;
			if (a[len] > b[i])
				__solution(len + 1, as + score, bs);
			else
				__solution(len + 1, as, bs + score);
			table[1][b[i]] = 0;
		}
	}
}

static void solution(void)
{
	for (int i = 0; i < 9; i++)
	{
		scanf("%d", &a[i]);
		table[0][a[i]] = 1;
	}

	for (int i = 1, j = 0; i <= 18; i++)
	{
		if (!table[0][i])
		{
			b[j++] = i;
		}
	}

	__solution(0, 0, 0);
	printf("%d %d\n", ans[0], ans[1]);
	memset(table, 0, sizeof(table));
	memset(ans, 0, sizeof(ans));
}

재귀를 이용하여 b가 만들 수 있는 모든 경우에 대하여 검증을 한다.

그리고 전달 받은 as, bs는 각각 a, b의 현재 점수를 의미하는데, 반복문을 돌면서 모든 경우에 대해 동일한 값을 유지해야 한다. 그래서 주석에 언급한 것 처럼 as, bs 자체의 값을 변경하지 않도록 코드를 구성해야 한다.

 

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

7088  (0) 2021.11.03
7194  (0) 2021.11.03
4012  (0) 2021.11.01
4013  (0) 2021.11.01
7466  (0) 2021.11.01