๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“• STUDY/Algorithm

[C / C++] ๋ฐฑ์ค€ 1316๋ฒˆ - ๊ทธ๋ฃน ๋‹จ์–ด ์ฒด์ปค

๋ฐฑ์ค€ 1316๋ฒˆ : https://www.acmicpc.net/problem/1260

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net


โœ… ๋ฌธ์ œ ์„ค๋ช…

๊ทธ๋ฃน๋‹จ์–ด๋ž€ ๋‹จ์–ด์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  ๋ฌธ์ž์— ๋Œ€ํ•ด์„œ ๊ฐ ๋ฌธ์ž๊ฐ€ ์—ฐ์†ํ•ด์„œ ๋‚˜ํƒ€๋Š” ๊ฒฝ์šฐ๋งŒ์„ ๋งํ•œ๋‹ค.

ccazzzzbb๋Š” c,a,z,b๊ฐ€ ๋ชจ๋‘ ์—ฐ์†์ ์œผ๋กœ ๋‚˜ํƒ€๋‚˜๋ฉฐ,

kin๋„ ํ•˜๋‚˜์”ฉ์ด์ง€๋งŒ k,i,n์ด ๋ชจ๋‘ ์—ฐ์†ํ•ด์„œ ๋‚˜์™”๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ฃน๋‹จ์–ด๋กœ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

 

๊ทธ๋Ÿฌ๋‚˜ aaccbbc๋Š” c๊ฐ€ ๋–จ์–ด์ ธ์„œ ๋‚˜ํƒ€๋‚ฌ๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ฃน๋‹จ์–ด๊ฐ€ ์•„๋‹ˆ๋‹ค.


โœ… ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ค๋ช…

1. ์•ŒํŒŒ๋ฒณ 26๊ฐœ๋ฅผ ํ™•์ธํ•˜๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค.

2. ์ž…๋ ฅ๋ฐ›์€ ๋‹จ์–ด์˜ ๊ธธ์ด๋งŒํผ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฆฐ๋‹ค.

 

-1) ๋‚˜์™”๋˜ ๋ฌธ์ž์ธ์ง€ ํ™•์ธํ•œ๋‹ค.

-2) ๋‚˜์™”๋˜ ๋ฌธ์ž๋ผ๋ฉด ๋ฐ”๋กœ ์ „ ๋ฌธ์ž์™€ ๊ฐ™์€์ง€ ํ™•์ธํ•˜์—ฌ, ์•„๋‹ˆ๋ฉด ๊ทธ๋ฃน ๋‹จ์–ด๊ฐ€ ์•„๋‹ˆ๋ผ๊ณ  ์ฒดํฌํ•จ

-3) ๋‚˜์™”๋˜ ๋ฌธ์ž๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด alpha ๋ฐฐ์—ด์—์„œ ํ•ด๋‹น ๋‹จ์–ด๋ฅผ ๋‚˜์™”๋‹ค๊ณ  ๋ฐ”๊พผ ํ›„ ๋‹ค์Œ ๋‹จ์–ด ํƒ์ƒ‰

 

3. ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜๋งŒํผ 2๋ฒˆ ๋ฐ˜๋ณต


โœ… ์ฝ”๋“œ

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;

int main(void) {
	int n, cnt = 0;
	scanf("%d", &n); // ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ ์ž…๋ ฅ

	/* ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต๋ฌธ */
	for (int i = 0; i < n; i++) {
		char word[101];
		scanf("%s", word); // ๋‹จ์–ด ์ž…๋ ฅ

		int alpha[26] = { 0, }; // ๋‚˜์™”๋˜ ๋ฌธ์ž์ธ์ง€ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•ด
		int flag = 0;
		for (int j = 0; j < strlen(word); j++) {
			if (alpha[word[j] - 'a'] == 1) { // ์ด๋ฏธ ๋‚˜์™”๋˜ ๋ฌธ์ž๋ผ๋ฉด
				if (word[j] != word[j - 1]) { // ๋ฐ”๋กœ ์ „ ๋ฌธ์ž์™€ ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด
					flag = 1; // ๊ทธ๋ฃน ๋‹จ์–ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ํƒˆ์ถœ
					break;
				}
			}
			else alpha[word[j] - 'a'] = 1; // ๋‚˜์˜จ ๋ฌธ์ž๋ผ๊ณ  ๋ฐ”๊พธ๊ธฐ
		}
		if (flag == 0) // ๊ทธ๋ฃน๋‹จ์–ด๋ผ๋ฉด cnt++
			cnt++;
	}
	printf("%d\n", cnt);
	return 0;
}

 

โšก alpha[ word[j] - ‘a’ ] = 1์ด ์˜๋ฏธํ•˜๋Š” ๊ฒƒ์€?

: ํ•ด๋‹น ๋ฌธ์ œ์—์„œ ๋‹จ์–ด๋Š” ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ค„์กŒ๋‹ค๊ณ  ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ.

ex) banana => word[0] = ‘b’

 

- word[0] - ‘a’ = ‘b’ - ‘a’

: ์•„์Šคํ‚ค์ฝ”๋“œ ๊ฐ’์œผ๋กœ 98 – 97 = 1์ด ๋‚˜์˜ด

 

- alpha[1] == ‘b’

: alpha[1] = 1๋กœ ๋ฐ”๊ฟ” ๋‚˜์™”๋˜ ๋‹จ์–ด๋ผ๊ณ  ํ‘œ์‹œํ•จ


https://github.com/2hyunjinn/Baekjoon/blob/main/Baekjoon_1316.cpp

 

GitHub - 2hyunjinn/Baekjoon

Contribute to 2hyunjinn/Baekjoon development by creating an account on GitHub.

github.com