UVA11732 “strcmp()“ Anyone?

2 篇文章 0 订阅

D e s c r i p t i o n Description Description

传送门(洛谷真香
n n n个字符串,求两两进行 s t r c m p strcmp strcmp函数比较的总次数
n ≤ 4000 , l e n ( s ) ≤ 1000 n\leq4000,len(s)\leq1000 n4000,len(s)1000

S o l u t i o n Solution Solution

把每个串加入 T i r e Tire Tire
d f s dfs dfs统计
串结尾的'\0'也要加进去

A c c e p t e d   c o d e Accepted\ code Accepted code

#include<cstdio>
#include<cstring>
#include<iostream>

#define int long long

using namespace std;

const int MAX_NODE = 4e6 + 5;

struct Line {
	int to, next;
}e[MAX_NODE];

char s[1005];
int n, k, ans, cnt, caze;
int num[MAX_NODE], last[MAX_NODE];

int read() {
	int f = 0; char c = getchar();
	while (!isdigit(c)) c = getchar();
	while (isdigit(c)) f = f * 10 + c - 48, c = getchar();
	return f;
}

int get_id(char c) {
	if (c >= '0' && c <= '9') return c - 48;
	if (c >= 'A' && c <= 'Z') return c - 55;
	if (c >= 'a' && c <= 'z') return c - 61;
	return 62;
}

void insert(char *s) {
	int p = 0, len = strlen(s); ++num[0];
	for (int i = 0; i <= len; ++i) {
		int c = get_id(s[i]);
		int j = last[p], flag = 0;
		for (; j; j = e[j].next)
			if (e[j].to == c) { flag = 1; break; }
		if (!flag)
			e[++cnt] = (Line){c, last[p]}, last[p] = j = cnt;
		++num[(p = j)];
	}
	return;
}

void dfs(int deep, int now) {
	if (!last[now]) { ans += num[now] * (num[now] - 1) * deep; return; }
	long long sum = 0;
	for (int i = last[now]; i; i = e[i].next)
		sum += num[i] * (num[now] - num[i]);
	ans += (sum >> 1) * (2 * deep + 1);
	for (int i = last[now]; i; i = e[i].next)
		dfs(deep + 1, i);
	return;
}

signed main() {
	while ((n = read()) != 0) {
		memset(num, 0, sizeof num);
		memset(last, 0, sizeof last);
		k = ans = cnt = 0;
		for (int i = 1; i <= n; ++i)
			scanf("%s", s), insert(s);
		dfs(0, 0);
		printf("Case %d: %lld\n", ++caze, ans);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值