LightOJ - 1322 - Worst Case Trie(DP)
链接:
https://vjudge.net/problem/LightOJ-1322
题意:
In Computer Science Trie or prefix tree is a data structure which is usually used to store some strings or some numbers. Unlike binary trees, edges contain characters. And a node actually represents a string which is found by taking the characters from the edges, in the path from root to leaf. For example, for {abc, ae, bd, bb, bc, abd} we get the following trie:
Now you are given a set of strings and each string uses one of the K character symbols, and in any string (from the set) a symbol occurs at most once. Your task is to find the number of nodes required if we make a trie with the strings, using the procedure described above. As you don't know the size of the set, your task is to find the worst case result. For example, if you have 2 character symbols, then you need 5 nodes in worst case as in the following trie (let the symbols be {a, b}):
思路:
对i个字符,他的每个分支都是i-1个字符,可以让i-1个字符的根节点变成i中的一个,再加上自己的根节点。
得到Dp[i] = i*Dp[i-1]+1
对于mod 10000,当点数mod 10000为0时答案为1,即答案又从1开始循环,所以直接将i%10000即可。
代码:
// #include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<vector>
#include<string.h>
#include<set>
#include<queue>
#include<algorithm>
#include<math.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int MOD = 1e9+7;
const int MAXN = 1e6+10;
int k;
int a[MAXN];
void Init()
{
a[0] = 1;
for (int i = 1;i < MAXN;i++)
a[i] = (a[i-1]*i+1)%10000;
}
int main()
{
// freopen("test.in", "r", stdin);
Init();
int t, cas = 0;
scanf("%d", &t);
while(t--)
{
scanf("%d", &k);
printf("Case %d:", ++cas);
if (k <= 5)
{
printf(" %d\n", a[k]);
continue;
}
k %= 10000;
printf(" %04d\n", a[k]);
}
return 0;
}