Ancient Printer(HDOJ 3460)

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
[/hint]

My Code

字典树这个算法很多时候都可以用map,这题嘛,连map都不用。。。

include 
#include 
#include 
using namespace std;
int n, ans, maxl;
string str[10005];
int solve(string a, string b)
{
    int i;
    int l1 = a.length();
    int l2 = b.length();
    for (i = 0; i < l1 && i < l2; i++)
        if (a[i] != b[i])               //i为公共部分长度
            break;                      //打印第二个字符串,先删去第一个字符串的非公共部分l1-i
    return l1 + l2 - 2 * i;             //再输入第二个字符串非公共部分l2-i
}
int main()
{
    while (cin >> n)
    {
        for (int i = 0; i < n; i++)
            cin >> str[i];
        sort(str, str + n);             //先将字符串从小到大排序
        ans = str[0].length() + 1;      //打印第一个字符串
        maxl = str[0].length();         //找最长的字符串
        for (int i = 1; i < n; i++)
        {
            ans += solve(str[i - 1], str[i]) + 1;   //最后还有一个打印键要按
            maxl = maxl > str[i].length() ? maxl : str[i].length();
        }
        cout << ans + str[n - 1].length() - maxl << endl; //最后的字符串不需要删所以留下最长的那条
    }                                                     //先把最后n-1那条删了然后再减去最长的那条就行了
    return 0;
}