逆序单词(Trie)

在英文中有很多逆序的单词,比如dog和god,evil和live等等。

现在给出一份包含N个单词的单词表,其中每个单词只出现一次,请你找出其中有多少对逆序单词。

Input

第1行:1个整数,N,表示单词数量。2≤N≤50,000。

第2..N+1行:每行1个单词,只包含小写字母,每个单词长度不超过16个字母。保证每个单词只出现一次,且不会出现回文单词(即一个单词倒序还是它自己,比如eye)。

Output

第1行:1个整数,表示单词表中逆序单词的对数。

Sample Input

6
dog
live
hiho
evil
coder
god

Sample Output

2

思路

放到Trie搞一搞

代码示例

指针

#include<bits/stdc++.h>
using namespace std;

const int charset=26;

struct Node
{
    Node *next[charset];
    int flag;
    Node(){
        for(int i=0;i<charset;++i){
            next[i]=NULL;
        }
        flag=0;
    }
};

Node *root;

void init()
{
    root= new Node();
}

void del(Node *p)
{
    for(int i=0;i<charset;++i){
        if(p->next[i]!=NULL) del(p->next[i]);
    }
    delete p;
}

char temp[20];

void ins(char *s)
{
    int len=strlen(s);
    Node *now=root;
    for(int i=0;i<len;++i){
        int to=s[i]-'a';
        if(now->next[to]==NULL) now->next[to]=new Node();
        now=now->next[to];
    }
    now->flag=1;
}

int fid(char *s)
{
    int len=strlen(s);
    Node *now=root;
    for(int i=len-1;i>=0;--i){
        int to=s[i]-'a';
        if(now->next[to]==NULL) return 0;
        now=now->next[to];
    }
    return now->flag;
}


int main()
{
    //ios::sync_with_stdio(false);
    //freopen("in.txt","r",stdin);
    init();
    int n;
    scanf("%d",&n);
    int ans=0;
    while(n--)
    {
        scanf("%s",temp);
        ins(temp);
        //reverse(temp,temp+strlen(temp));
        //cout<<temp<<endl;
        ans+=fid(temp);
    }
    printf("%d\n",ans);
    del(root);
    return 0;
}



数组

#include<bits/stdc++.h>
using namespace std;

const int charset=26;
const int maxn=1e6+10;

int Trie[maxn][charset];

bool flag[maxn];
int cnt;
int root;

void init()
{
    root=0;
    cnt=0;
}

void del()
{
    memset(Trie,0,sizeof(Trie));
    memset(flag,0,sizeof(flag));
}

char temp[20];

void ins(char *s)
{
    int len=strlen(s);
    int now=root;
    for(int i=0;i<len;++i){
        int to=s[i]-'a';
        if(Trie[now][to]==0) Trie[now][to]=++cnt;
        now=Trie[now][to];
    }
    flag[now]=1;
}

int ans=0;

void fid(char *s)
{
    int len=strlen(s);
    int now=root;
    for(int i=len-1;i>=0;--i){
        int to=s[i]-'a';
        if(Trie[now][to]==0) return ;
        now=Trie[now][to];
    }
    ans+=flag[now];
}


int main()
{
    //ios::sync_with_stdio(false);
    //freopen("in.txt","r",stdin);
    init();
    int n;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",temp);
        ins(temp);
        //reverse(temp,temp+strlen(temp));
        //cout<<temp<<endl;
        fid(temp);
    }
    printf("%d\n",ans);
    del();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值