LightOJ 1224 DNA Prefix

24 篇文章 0 订阅
21 篇文章 0 订阅
  这题用的是字典树,把所有的字符串输入到字典树中,设置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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值