zoukankan      html  css  js  c++  java
  • Hdoj 1671

    原题链接

    描述

    Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:

    1. Emergency 911
    2. Alice 97 625 999
    3. Bob 91 12 54 26

    In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.

    输入

    The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

    输出

    For each test case, output “YES” if the list is consistent, or “NO” otherwise.

    样例输入

    2
    3
    911
    97625999
    91125426
    5
    113
    12340
    123440
    12345
    98346

    样例输出

    NO
    YES

    思路

    字典树
    令人悲伤,数组形式的字典树MLE了,把数组大小改小又WA,原以为只能用链表了,群里大佬说能用vector形式!
    我以前没用过vector,赶紧百度学了一下,上手套模版,稍微改动一下就好。期间犯了很多很傻的错误,比如忘记给vector迭代下去之类的,觉得自己好渣啊~

    代码

    #include <bits/stdc++.h>
    #define maxn 900000
    using namespace std;
    
    struct node
    {
    	int a[10];
    };
    
    vector<node> trie;
    int cnt[maxn], tot, f;
    
    void create(char st[])
    {
    	int len = strlen(st);
    	int u = 0;
    	for(int i = 0; i < len; i++)
    	{
    		if(trie[u].a[st[i] - '0'] == 0)
    		{
    			trie[u].a[st[i] - '0'] = ++tot;
    			node pnew; 
    			for(int j = 0; j <10; j++) pnew.a[j] = 0;
    			trie.push_back(pnew);
    		}
    		u = trie[u].a[st[i] - '0'];
    		if(cnt[u]) f = 1;
    	}
    	cnt[u] = 1;
    	for(int i = 0; i < 10; i++) 
    		if(trie[u].a[i]) f = 1;
    }
    
    int main()
    {
    	int num; scanf("%d", &num);
    	while(num--)
    	{
    		trie.clear();
    		memset(cnt, 0, sizeof(cnt));
    		f = 0; tot = 0;
    		node pnew; for(int j = 0; j <10; j++) pnew.a[j] = 0;
    		trie.push_back(pnew);
    		int n;
    		scanf("%d", &n);
    		for(int i = 0; i < n; i++)
    		{
    			char st[12]; scanf("%s", st);
    			if(f == 0) create(st);
    		}
    		if(f == 0) printf("YES
    ");
    		else printf("NO
    ");
    	}
    	return 0;
    }
    
  • 相关阅读:
    【转载】常考算法模板
    NOIP2020微信步数暴力80分
    NOIP2020移球游戏快速排序满分程序
    第一场NOI Online能力测试入门组B跑步
    【转】STL之Set——插入元素、二分查找元素(log级别)
    [转载]图论500题
    差分约束系统简单介绍(入门)
    辗转相除法的证明
    并查集2个优化——按秩合并和路径压缩
    递推算法之平面分割问题总结
  • 原文地址:https://www.cnblogs.com/HackHarry/p/8379377.html
Copyright © 2011-2022 走看看