답안 #676015

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
676015 2022-12-28T21:14:27 Z as111 Rima (COCI17_rima) C++14
0 / 140
105 ms 262144 KB
//tries data structure, can be used for prefixes, etc.
#include <iostream>
#include <vector>

#define MAXN 300000

using namespace std;

struct Trie {
	int nex[26]; // index of next trie for each letter
	int prev; // parent
	bool end; // end of a word
	int mx; // max path
	Trie() {
		fill(nex, nex + 26, -1);
		prev = -1;
	}
};

Trie tries[MAXN * 20 + 5];
int N;
char letters[200];
int index = 1;
int ans = 0;
void traverse(int curr) {
	int children = 0;
	int maxchild = 0;
	int maxchild2 = 0; // top 2 max children
	for (int c = 0; c < 26; c++) { // loop through each letter
		int next = tries[curr].nex[c];
		if (next != -1) {
			traverse(next);
			if (tries[next].end) { // next is an end, otherwise don't connect to curr
				if (tries[next].mx > maxchild) {
					maxchild2 = maxchild;
					maxchild = tries[next].mx;
				}
				else if (tries[next].mx > maxchild2) {
					maxchild2 = tries[next].mx;
				}
				children++;
			}
		}
	}
	if (children > 1) {
		tries[curr].mx += maxchild + children - 1; // can visit all siblings before moving down to curr
		ans = max(ans, tries[curr].mx + maxchild2 - 1); // connect second longest path
	}
	else {
		tries[curr].mx += maxchild;
		ans = max(ans, tries[curr].mx);
	}
}
int main() {
	cin >> N;
	for (int i = 0; i < N; i++) {
		string str;
		cin >> str;
		int curr = 0;
		for (int j = (int)str.length() - 1; j >= 0;j--) {
			int c = (int)str[j] - 97;
			letters[c] = str[j];
			if (tries[curr].nex[c] != -1) { // prefix recorded previously
				curr = tries[curr].nex[c];
			}
			else {
				tries[curr].nex[c] = index;
				tries[index].prev = curr;
				curr = index;
				index++;
			}
		}
		tries[curr].end = true;
		tries[curr].mx = 1; // count word itself
	}
	traverse(0);
	cout << ans;
}
# 결과 실행 시간 메모리 Grader output
1 Runtime error 102 ms 262144 KB Execution killed with signal 9
2 Runtime error 102 ms 262144 KB Execution killed with signal 9
3 Runtime error 104 ms 262144 KB Execution killed with signal 9
4 Runtime error 101 ms 262144 KB Execution killed with signal 9
5 Runtime error 99 ms 262144 KB Execution killed with signal 9
6 Runtime error 102 ms 262144 KB Execution killed with signal 9
7 Runtime error 102 ms 262144 KB Execution killed with signal 9
8 Runtime error 105 ms 262144 KB Execution killed with signal 9
9 Runtime error 105 ms 262144 KB Execution killed with signal 9
10 Runtime error 101 ms 262144 KB Execution killed with signal 9