HDU 3460 Ancient Printer

Problem Description

The contest is beginning! While preparing the contest, iSea wanted to print the teams' names separately on a single paper.
Unfortunately, what iSea could find was only an ancient printer: so ancient that you can't believe it, it only had three kinds of operations:

● 'a'-'z': twenty-six letters you can type
● 'Del': delete the last letter if it exists
● 'Print': print the word you have typed in the printer

The printer was empty in the beginning, iSea must use the three operations to print all the teams' name, not necessarily in the order in the input. Each time, he can type letters at the end of printer, or delete the last letter, or print the current word. After printing, the letters are stilling in the printer, you may delete some letters to print the next one, but you needn't delete the last word's letters.
iSea wanted to minimize the total number of operations, help him, please.

Input

There are several test cases in the input.

Each test case begin with one integer N (1 ≤ N ≤ 10000), indicating the number of team names.
Then N strings follow, each string only contains lowercases, not empty, and its length is no more than 50.

The input terminates by end of file marker.

Output

For each test case, output one integer, indicating minimum number of operations.

Sample Input

2
freeradiant
freeopen

Sample Output

21

Hint

The sample's operation is:

f-r-e-e-o-p-e-n-Print-Del-Del-Del-Del-r-a-d-i-a-n-t-Print

字典树统计不同字母的次数,每个不同字母一定会打出两遍,然后最长的最后输出。

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 500005;
int T, n, tot, ans;
char s[maxn];

struct tire
{
	int num[26];
	int sum;
	int operator[](int &x){ return num[x]; }
	void insert(int x, int y){ num[x] = y; }
	void clear(){ sum = 0; memset(num, 0, sizeof(num)); };
}f[maxn];

int main()
{
	while (scanf("%d", &n) != EOF)
	{
		f[0].clear();
		for (int i = tot = ans = 0; i < n; i++)
		{
			scanf("%s", s);
			if (ans < strlen(s)) ans = strlen(s);
			for (int j = 0, k = 0; s[j]; j++)
			{
				int u = s[j] - 'a';
				if (!f[k][u])
				{
					f[k].insert(u, ++tot);
					f[tot].clear();
				}
				k = f[k][u];
			}
		}
		printf("%d\n", tot + tot - ans + n);
	}
	return 0;
}


你可能感兴趣的:(HDU,字典树)