ZOJ-1875-Phone List-字典樹

來源:互聯網
上載者:User

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1875

 

思路:字典樹判斷首碼,插入號碼的時候就開始判斷,一旦出現重複首碼,之後的號碼就不進行插入操作(經過實踐,實踐實踐相差10ms而已)

這題只要拿字典樹的模板,然後稍加修改就能AC,另外再加上del(root)釋放一下

#include "cstdlib"<br />#include "cctype"<br />#include "cstring"<br />#include "cstdio"<br />#include "cmath"<br />#include "algorithm"<br />#include "vector"<br />#include "string"<br />#include "iostream"<br />#include "sstream"<br />#include "set"<br />#include "queue"<br />#include "stack"<br />#include "fstream"<br />#include "iomanip"<br />#include "bitset"<br />#include "list"<br />#include "ctime"<br />using namespace std;<br />struct Trie{<br />Trie *child[10];<br />int data, flag;<br />Trie(){<br />for(int i = 0; i < 10; i++)<br />child[i] = NULL;<br />flag = data = 0;<br />}<br />};<br />bool insert(Trie *&root, char *s){<br />int i, idx;<br />Trie *cur = root;<br />if(cur == NULL){<br />cur = new Trie();<br />root = cur;<br />}<br />for(i = 0; s[i]; i++){<br />idx = s[i] - '0';<br />if(cur->child[idx] == NULL){<br />cur->child[idx] = new Trie();<br />}<br />cur = cur->child[idx];<br />if(cur->flag)<br />return false;<br />cur->data++;<br />}<br />cur->flag = 1;<br />if(cur->data > 1)<br />return false;<br />return true;<br />}<br />void del(Trie *root){<br />if(root){<br />for(int i = 0; i < 10; i++){<br />del(root->child[i]);<br />}<br />delete(root);<br />}<br />}<br />int main(){<br />int t, n, i, ans;<br />char num[20];<br />scanf("%d",&t);<br />Trie *root;<br />while(t--){<br />root = NULL;<br />scanf("%d",&n);<br />ans = 1;<br />for(i = 0; i < n; i++){<br />scanf("%s",num);<br />if(!insert(root, num)){<br />ans = 0;<br />i++;<br />break;<br />}<br />}<br />for(; i < n; i++)<br />scanf("%s",num);<br />if(ans)<br />puts("YES");<br />else<br />puts("NO");<br />del(root);<br />}<br />return 0;<br />}<br />

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.