uva11732

本文探讨了使用C++编程实现的字符串插入算法,通过构造动态树结构来高效管理字符插入对计数和子树的影响。核心内容涉及`NodeId`获取、树的初始化、插入操作及最终答案计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
int n,cnt = 0;
long long int ans = 0;
const int maxn = 4000007;
char ch[1007];

struct Node
{
	int nx[64];
	int cnt;
}tree[maxn];

void Init() {
	cnt = 1;
	ans = 0;
	memset(&tree[1], 0, sizeof(Node));
}
int GetId(char input) {
	if (input == '\0') return 0;
	else if (input >= '0' && input <= '9') return 1 + input - '0';
	else if (input >= 'A' && input <= 'Z') return 11 + input - 'A';
	else return input - 'a' + 37;
}

void Insert(char* input) {
	int cur = 1,id = 0,isNew = 0;

	int len = strlen(input);
	int last = tree[cur].cnt;

	for (int i = 0; i <= len; i++) {
		id = GetId(input[i]);

		if (tree[cur].nx[id] == 0) {
			memset(&tree[cnt + 1], 0, sizeof(Node));
			tree[cur].nx[id] = ++cnt;
			if (!isNew) ans += last;
			isNew = 1;
		}
		else {
			int nx = tree[cur].nx[id];
			ans += last - tree[nx].cnt;
			ans += tree[nx].cnt * 2;
		}
		cur = tree[cur].nx[id];
		last = tree[cur].cnt;
		tree[cur].cnt++;
	}
	tree[1].cnt++;
}

static auto speedup = [](){ios::sync_with_stdio(false);cin.tie(nullptr);return nullptr;}();
int main()
{
	int kCase = 0;
	while (cin >> n && n) {
		Init();
		for (int i = 0; i < n; i++) {
			cin >> ch;
			Insert(ch);
		}
		cout <<"Case " << ++kCase << ": " <<  ans << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值