Trie UVA 11732 "strcmp ()" Anyone?

Source: Internet
Author: User

Topic Portal

Test instructions: Ask for the comparison of all strings and (note the comparison within the For loop)

Analysis: Inserting all the strings into the dictionary tree, and then the node information records a few strings, then every time you go to a node you will know how many times you need to compare to this point. Learn to link table Save node

#include <bits/stdc++.h>using namespace Std;typedef long long ll;const int N = 4e3 + 5;const int M = 1e3 + 5;const I NT NODE = N * m;struct trie{int Head[node], Nex[node];char ch[node];int cnt[node];int sz;void Clear () {sz = 1;cnt[0] = Head [0] = nex[0] = 0;} void Insert (char *str) {int u = 0, len = strlen (str), cnt[0]++;for (int i=0; i<=len; ++i) {bool found = False;int v;for ( V=head[u]; V V=nex[v]) {if (ch[v] = = Str[i]) {found = True;break;}} if (!found) {//INSERT into the list of head nodes after a V = sz++;cnt[v] = 0;ch[v] = Str[i];nex[v] = Head[u];head[u] = V;head[v] = 0;} u = v;cnt[u]++;}}            void query (int u, int dep, LL &res) {if (!head[u]) {res + = cnt[u] * (Cnt[u]-1) * DEP; return;}            int sum = 0, TMP = cnt[u];for (int v=head[u]; v; v=nex[v]) {//sum + = cnt[v] * (Cnt[u]-cnt[v]);        Res + = cnt[v] * (Tmp-cnt[v]) * (DEP * 2 + 1); tmp-= cnt[v]; }//res + = SUM/2 * (2 * dep + 1); for (int v=head[u]; v; v=nex[v]) {query (V, DEP + 1, res);}}} Trie;char Word[m];int Main (void) {int n, cas = 0;while (scanf ("%d", &n) = = 1) {if (!n) break;trie.clear (); for (int i=0; i<n; ++i) {scanf ("%s", &am P;word); Trie.insert (word);} ll ans = 0;trie.query (0, 0, ans);p rintf ("Case%d:%lld\n", ++cas, ans);} return 0;}

  

Trie UVA 11732 "strcmp ()" Anyone?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.