Simple prefix compression 问题

/*
Simple prefix compression
 总时间限制: 2000ms 内存限制: 65536kB
描述
Many databases store the data in the character fields (and especially indices) using prefix compression. This technique compresses a sequence of strings A1, ..., AN by the following method: if there are strings Ai = ai,1ai,2...ai,p and Ai + 1 = ai+1,1ai+1,2...ai+1,q 
such that for some j ≤ min(p, q) ai,1 = ai+1,1, ai,2 = ai+1,2, ... ai,j = ai+1,j, then the second string is stored as [j]ai+1,j+1ai+1,j+2... ai+1,q, where [j] is a single character with code j. 

If j = 0, that is, strings do not have any common prefix, then the second string is prefixed with zero byte, and so the total length actually increases.


Constraints
1 ≤ N ≤ 10000, 1 ≤ length(Ai) ≤ 255.
输入
First line of input contains integer number N, with following N lines containing strings A1 ... AN
输出
Output must contain a single integer -- minimal total length of compressed strings.
样例输入
3
abc
atest
atext
样例输出
11
来源
Northeastern Europe 2003, Far-Eastern Subregion
这周学的是递归,但是这题好像不用递归做直接模拟就可以了,不过这样AC的结果内存较大4564kB,用时370ms
作者1300012964
*/
#include
#include
#include
#include
using namespace std;
int main()
{
	int n;
	int total = 0;
	int len[10002];
	string str[10002];
	scanf("%d",&n);
	for(int i = 0; i < n; ++i)
	{
		cin >> str[i];
		len[i] = str[i].size();
		total += len[i];   //首先将所有的长度加起来
	}
	for(int i = 0; i < n - 1; ++i)
	{
		for(int j = 0; j < min(len[i],len[i+1]); ++j)
		{
			if(str[i][j] == str[i+1][j])   //碰到相同则长度减一
				--total; 
			else
				break;
		}
		++total;  		//减去头字母的影响,加一
	}
	printf("%d\n",total);
	return 0;
}


你可能感兴趣的:(程序设计实习)