Question Link
The topic description is simple: there are N and DNA sequences, and find the maximum value of their public prefix length and the product of the same public prefix DNA sequence.
If we take the subset {acgt} then the result is 4 (4*1), if we take {acgt, acgtgcgt, acgccgt} then the result is 3*3 = 9 (since ACG is the common prefix ),
If we take {acgt, acgtgcgt, accgtgc, acgccgt} then the result is 2*4 = 8.
This is an English description. It is very simple and will not be translated.
Ideas:
This topic is obviously done using trie. I think so. Using trie to store all the DNA sequences, then each node has a CNT value, indicates the number of DNA sequences ending with the node.
In the input process, the building process is started. Finally, I used recursion in the query results, and the code is easy to write and understand.
Finally, although we seldom use pointers in the competition, we must release pointers after they are used up. Otherwise, we will use MLE twice.
Code:
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;struct trie{ struct trie *next[5]; int cnt;} *p;trie* newtrie(){ trie *q = new trie(); for (int i = 0; i < 4; i++) q->next[i] = NULL; q->cnt = 0; return q;};void insert(char *str, trie *root){ p = root; while (*str) { int pos; if (*str == 'A') pos = 0; else if (*str == 'C') pos = 1; else if (*str == 'G') pos = 2; else pos = 3; if (!p->next[pos]) { p->next[pos] = newtrie(); p = p->next[pos]; p->cnt++; } else { p = p->next[pos]; p->cnt++; } str++; }}int maxnum(struct trie *q, int d){ int maxn = d * q->cnt; for (int i = 0; i < 4; i++) { if (q->next[i]) { maxn = max(maxn, maxnum(q->next[i], d+1)); } } return maxn;}void moveit(trie *root){ if (root == NULL) return; for (int i = 0; i < 4;i++) { moveit(root->next[i]); } free(root);}int main(){ int t, n; char s[55]; scanf("%d",&t); for(int k = 1; k <= t; k++) { trie *root = newtrie(); scanf("%d",&n); while (n--) { scanf("%s",s); insert(s, root); } printf("Case %d: %d\n", k, maxnum(root, 0)); moveit(root); } return 0;}