跳到正文

题解

题解:CF858D Polycarp's phone book

MitchellZhong约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年9月14日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟
题目
CF858D

版本

  1. v1当前

CF858D Solution

不是怎么时间限制这么久。

这道题是我在做某题单时刷到的。

回到正题:我们发现数据量并不大,所以会去枚举每一个字符串的子串并检查它们是否被用过。

那么检查是否被用过就立马可以想到使用 map,但是其实也能用字典树。

首先过一下流程:

1.将每一个字符的字串加入到字典树中并记录有多少个。

2.对于每一个字符串的子串检查是否有出现过(先枚举长度,在枚举起始点。因为要求长度最短。)。

3.对于每个字符串输出第一个检查成功的字符串。

好的,至此我们已经知道了本题的大概思路并写出了这样一个代码:

C++
#include <bits/stdc++.h>
using namespace std;
int n;
string s[70005];
int nxt[1000005][10];
int vis[1000005];
int cnt=0;
int ctoi(char x){
	return x-'0';
}
void insert(string s){
	int p=0;
	for(auto i : s){
		int x=ctoi(i);
		if(!nxt[p][x]){
			nxt[p][x]=++cnt;
		}
		p=nxt[p][x];
	}
	vis[p]++;//枚举字串后加入字典树
}
bool find(string s){
	int p=0;
	for(auto i : s){
		int x=ctoi(i);
		p=nxt[p][x];
	}
	return vis[p];//返回有多少个相同含有这个子串的字符串
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>s[i];
	}
	for(int i=1;i<=n;i++){
		for(int l=1;l<=9;l++){
			for(int j=0;j+l-1<9;j++){
				insert(s[i].substr(j,l));
			}
		}
	}
	for(int i=1;i<=n;i++){
		bool flg=0;
		for(int l=1;l<=9;l++){
			for(int j=0;j+l-1<9;j++){
//				cout<<s[i].substr(j,l)<<" "<<find(s[i].substr(j,l))<<endl;
				if(find(s[i].substr(j,l))==0){
					cout<<s[i].substr(j,l)<<endl;
					flg=1;
					break;
				}
			}
			if(flg) break;
		}
	}
	return 0;
}

然后你就会兴高采烈地 WA 了。

这是怎么回事呢?

因为我们会发现在枚举判断时会记录到当前的字符串,所以就根本不会输出任何东西。

所以有两种方法:

1.在统计前把这个字符串的所有子串删掉,在统计后加回来。

C++
void Delete(string s){
	int p=0;
	for(auto i : s){
		int x=ctoi(i);
		p=nxt[p][x];
	}
	vis[p]--;
}
...
for(int i=1;i<=n;i++){
	for(int l=1;l<=9;l++){
		for(int j=0;j+l-1<9;j++){
			Delete(s[i].substr(j,l));
		}
	}
	bool flg=0;
	for(int l=1;l<=9;l++){
		for(int j=0;j+l-1<9;j++){
//				cout<<s[i].substr(j,l)<<" "<<find(s[i].substr(j,l))<<endl;
			if(find(s[i].substr(j,l))==0){
				cout<<s[i].substr(j,l)<<endl;
				flg=1;
				break;
			}
		}
		if(flg) break;
	}
	for(int l=1;l<=9;l++){
		for(int j=0;j+l-1<9;j++){
			insert(s[i].substr(j,l));
		}
	}
//		cout<<endl;
}

2.将判断条件改为 find(s[i].substr(j,l))==1。

那至此我们就可以 AC 本题了。

完结撒花!!!

原文