LightOJ 1224 DNA Prefix

  這題用的是字典樹,把所有的字符串輸入到字典樹中,設置len和v兩個參數,代表長度和字符串個數,遍歷找這兩個參數的最大積。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define mem(a) memset(a, 0, sizeof(a))
#define maxn 50
using namespace std;

char ch[maxn];
long maxs;

struct trie_tree
{
	int len;
	long v;
	trie_tree *next[4];
};

struct trie_tree *root;

int has(char chs)
{
    if(chs == 'A')
	return 0;
	else if(chs == 'C')	
	return 1;
	else if(chs == 'G')
	return 2;
	else
	return 3;
}

void null(struct trie_tree *q)
{
	int i;
	for(i = 0;i < 4;i++)
	q->next[i] = NULL;
	return;
}

void add()
{
	int i = 0;
	struct trie_tree *q;
	q = root;
	while(ch[i])
	{
	    if(q->next[has(ch[i])] == NULL)
	    {
    		q->next[has(ch[i])] = (struct trie_tree *)malloc(sizeof(struct trie_tree));
	        null(q->next[has(ch[i])]);
	        q->next[has(ch[i])]->len = q->len + 1;
	        q->next[has(ch[i])]->v = 1;
	        q = q->next[has(ch[i])];
	        i++;
    	}
    	else
    	{
    		q->next[has(ch[i])]->v++;
	    	q = q->next[has(ch[i])];
	    	i++;
	    }
	}
}

void res(struct trie_tree *q)
{
	int i;
	if(q != NULL)
	{
		if(maxs < (q->v * q->len))
		maxs = q->v * q->len;
		for(i = 0;i < 4;i++)
		{
			res(q->next[i]);
		}
	}
	return;
}

void deal(struct trie_tree *q)
{
	int i;
	for(i = 0;i <= 3;i++)
	{
		if(q->next[i] != NULL)
		{
			deal(q->next[i]);
		}
	}
	free(q);
	return;
}

int main(int argc, char *argv[])
{
	int cas, o = 0, i;
    long n;
    scanf("%d", &cas);
    while(cas--)
    {
    	maxs = 0;
    	root = (struct trie_tree *)malloc(sizeof(struct trie_tree));
    	null(root);
    	for(i = 0;i < 4;i++)
    	root->len = 0;
    	scanf("%ld", &n);
    	for(i = 0;i < n;i++)
    	{
    		mem(ch);
	    	scanf("%s", ch);
	    	add();
	    }
	    res(root);
	    printf("Case %d: %ld\n", ++o, maxs);
	    deal(root);
    }
	return 0;
}

發佈了72 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章