백준 1544 c++

magicdrill·2024년 8월 13일
0

백준 문제풀이

목록 보기
415/654

백준 1544 c++

쉬운 문제인데 너무 오래 걸렸다.
큐를 사용하지 않고, 부분문자열 함수를 사용했다.
map을 사용해 사이클 단어가 아닌 해로운 단어일 경우에만 map에 추가했다.
아주 미세하게 시간과 메모리 사용에서 다른 c++ 풀이보다 많이 나왔다.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <map>

using namespace std;

void input_voca(vector <string> &voca)
{
	int N, i;
	string temp;

	cin >> N;
	for (i = 0; i < N; i++)
	{
		cin >> temp;
		voca.push_back(temp);
	}
	/*for (i = 0; i < N; i++)
	{
		cout << voca[i] << "\n";
	}*/

	return;
}

void find_answer(vector <string> &voca)
{
	int i, j, k, count = 0;
	string current_str, compare_word, temp;
	map <string, int> answer;
	bool find = false;

	answer[voca[0]] = 1;
	for (i = 1; i < voca.size(); i++)
	{
		find = false;
		current_str = voca[i];
		//cout << "current_str : " << current_str << "\n";
		//map에 저장된 first와 current_str 비교
		for (auto compare : answer)//map에 대해서 반복순회
		{
			compare_word = compare.first;
			//cout << "compare_word : " << compare_word << "\n";
			for (k = 0; k < current_str.length(); k++)
			{
				if (current_str[k] == compare_word.front())
				{
					temp = current_str.substr(k) + current_str.substr(0, k);
					//cout << "temp : " << temp << "\n";
					if (temp == compare_word)//사이클 단어를 찾음
					{
						find = true;
						break;//순회 탈출
					}
					else//아니면 계속 순회
					{
						;
					}
				}
			}
			if (find)//사이클 단어를 찾음
			{
				compare.second++;
				break;//map에 대한 순회 탈출
			}
			else
			{
				;
			}
		}
		if (!find)//사이클 단어가 아님을 확인함
		{
			answer[current_str] = 1;
		}
	}
	//cout << "\n입력결과\n";
	for (auto ans : answer)
	{
		//cout << ans.first << " : " << ans.second << "\n";
		count += ans.second;
	}
	cout << count << "\n";

	return;
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	vector <string> voca;

	input_voca(voca);
	find_answer(voca);

	return 0;
}

0개의 댓글