HDU-1004 Let the Balloon Rise

来源:互联网 发布:公司名义开淘宝店 编辑:程序博客网 时间:2024/05/24 06:30

可以用map做,这里用的是Trie树

#include <cstdio>#include <iostream>#include <cstdlib>#include <string>using namespace std;typedef struct node {    struct node* next[26];    int value;    int num;} Node;Node* createTrie() {    Node* root = ( Node* )malloc( sizeof( Node ) );    for( int i = 0; i < 26; i++ ) {        root->next[i] = NULL;    }    root->value = root->num = 0;    return root;}void insert( Node* root, string str ) {    Node* r = root;    for( int i = 0; i < str.size(); i++ ) {        if( r->next[str[i] - 'a'] == NULL ) {            Node* p = createTrie();            r->next[str[i] - 'a'] = p;        }        r = r->next[str[i] - 'a'];        //r->num++;    }    r->num++;    r->value = 1;}int find( Node* root, string str ) {    Node* r = root;    for( int i = 0; i < str.size(); i++ ) {        if( r->next[str[i] - 'a'] == NULL ) return 0;        r = r->next[str[i] - 'a'];    }    return r->num;}int main() {    int n;    while( scanf( "%d", &n ) != EOF && n ) {        Node* root = createTrie();        string str[1005];        char ch = getchar();        for( int i = 0; i < n; i++ ) {            cin >> str[i];            insert( root, str[i] );        }        int Max = -1;        int index = -1;        for( int i = 0; i < n; i++ ) {            int cur = find( root, str[i] );            //cout << str[i] << "=";            //printf( "%d\n", cur );            if( cur > Max ) {                Max = cur;                index = i;            }        }        cout << str[index] << endl;    }    return 0;}


0 0
原创粉丝点击