프로그래밍 알고리즘

[정올 1535] 단어집합2

꾸준한사람 2023. 1. 5. 02:31
반응형

http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=807&sca=99&sfl=wr_hit&stx=1535 

 

JUNGOL

 

www.jungol.co.kr

#include <stdio.h>

struct Node {
	Node* pPrev, *pNext;
	int len;
	char* pWord;
	Node() : pPrev(nullptr), pNext(nullptr), len(0), pWord(nullptr) {}
	Node(Node* prev, Node* next) : pPrev(prev), pNext(next), len(0), pWord(nullptr) {
		prev->pNext = next->pPrev = this;
	}
} H, T;

char stc[55];

bool IsSame(const char* pA, const char* pB, int len) {
	for (int i = 0; i < len; i++)
		if (pA[i] != pB[i]) return false;
	return true;
}

bool input() {
	for (int i = 0; i < 55; i++) stc[i] = 0;
	fgets(stc, sizeof(stc), stdin);
	if (IsSame("END", stc, 3)) return false;
	else return true;
}

bool NeedToAdd(int idx, int len) {
	for (Node* pN = H.pNext; pN != &T; pN = pN->pNext) {
		if (len != pN->len) continue;
		if (IsSame(pN->pWord, stc + idx, len)) return false;
	}
	return true;
}

int main(void) {
	H.len = -1; T.len = -2;
	H.pNext = &T; T.pPrev = &H;

	while (input()) {
		for (int i = 0, j = 0; stc[i] != '\n' && stc[i] != 0; i += j + 1) {
			for (j = 0; stc[i + j] != ' ' && stc[i + j] != '\n'; j++) {}
			if (NeedToAdd(i, j)) {
				Node* pNew = new Node(T.pPrev, &T);
				pNew->len = j;
				pNew->pWord = new char[j + 1];
				for (int k = 0; k < j; k++) pNew->pWord[k] = stc[i + k];
				pNew->pWord[j] = 0;
			}
		}
		for (Node* pN = H.pNext; pN != &T; pN = pN->pNext)
			printf("%s ", pN->pWord);
		printf("\n");
	}

	return 0;
}
반응형