Main topic:
Enter multiple strings of numbers to determine if the number string is the prefix of the other strings. If output no is present, the output is yes.
Problem Solving Ideas:
Use Trie to build a dictionary tree, then Mark 1 at the end of each number string, and then judge each string by entering it. Whether there is a previous sign mark.
#include <iostream> #include <malloc.h> #include <cstring> #include <cstdio>using namespace std ; const int Max_len = 11;typedef struct trie{trie *next[10]; int num;} T T *tree;bool flag;void Triedel (t *p) {for (int i=0;i<10;i++) {if (p->next[i]!=null) Triedel (P->next[i]); } free (p);} void Trieinsert (char str[]) {T *p=tree,*q; int Len=strlen (str); for (int i=0;i<len;i++) {int id=str[i]-' 0 '; if (p->next[id]==null) {q=new T; for (int j=0;j<10;j++) q->next[j]=null; q->num=0; p->next[id]=q; p=p->next[id]; } else p=p->next[id]; if (P->num = = 1) flag =false; } p->num=1; for (int i=0;i<10;i++) {if (p->next[i]!=null) {flag=false; Break }}}void init () {tree = new T; for (int i=0;i<10;i++) {tree->next[i]=null; }}int Main () {int cas; scanf ("%d", &cas); while (cas--) {flag=true; int n; scanf ("%d", &n); GetChar (); Init (); for (int i=0;i<n;i++) {char Str[max_len]; Gets (str); if (!flag) continue; Trieinsert (str); } triedel (tree); if (flag) printf ("yes\n"); else printf ("no\n"); } return 0;}
The following code does not use a dictionary tree:
#include <iostream> #include <algorithm> #include <map> #include <set> #include <vector># include<stack> #include <string> #include <queue> #include <cstdio> #include <cstring># include<cmath> #include <cctype>typedef unsigned long long ull;typedef long long ll;using namespace std; String Inp[10010];bool Solve (const string &a, const string & B) {if (A.length () > B.length ()) return F Alse; for (unsigned i = 0; i < a.length (); ++i) if (a[i]! = B[i]) return false; return true;} int main () {int t; CIN >>t; while (t--) {int n; bool Bol = true; CIN >> N; for (int i = 0; i < n; ++i) cin >> Inp[i]; Sort (INP, INP + N); for (int i = 0; i < n; ++i) if (Solve (Inp[i], inp[i+1]) Bol = false; cout << (bol? ") YES ":" NO ") <<endl; } return 0;}
HDU1671 Phone List (dictionary tree)