跳到正文

题解

P13393 File Fix-it 题解

SunShine2012约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟
获赞
1
题目
P13393

版本

  1. v1当前

题目分析

看到“目录”,立刻想到可以用多叉树的方法做(多叉树有模板)。

多叉树模板‌

C++
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const ll _p = 100;
vector<string> vec;
class node{
private:
	string father;
public:
	map<string, node*> sons;
	node(string _father): father(_father){}
	void insert(ll x){
		if (x >= vec.size()) return;
		string dir = vec[x];
		if (sons.find(dir) == sons.end()) sons[dir] = new node(dir);
	}
};
class tree{
private:
	node* root;
public:
	tree(){root = new node("");}
	void insert(){
		node* tmp = root;
		for (string& dir : vec){
			if (tmp->sons.find(dir) == tmp->sons.end()) tmp->sons[dir] = new node(dir);
			tmp = tmp->sons[dir];
		}
	}
};
signed main(){
  ;
  return 0;
}

现在我们可以看到,我们还需要:

  • 分割目录的函数 split;
  • 计算命令数量的函数 tree::count。

split 函数

想到 getline 函数可以获取到特定字符,于是结合 stringstream 读取目录,存到 vec 里。

C++
void split(){
	vec.clear();
	char p[_p];
	scanf("%s", p);
	stringstream ss(p);
	string s;
	while (getline(ss, s, '/')) if (!s.empty()) vec.push_back(s);
}

node::insert tree::count 函数

一边建树一边计算。

C++
ll insert(ll x){
	if (x >= vec.size()) return 0;
	string dir = vec[x];
	ll cnt = 0;
	if (sons.find(dir) == sons.end()) sons[dir] = new node(dir), cnt = 1;
	return cnt + sons[dir]->insert(x + 1);
}
C++
ll count(){
	return root->insert(0);
}

主函数

用 ansans 统计答案。

C++
signed main(){
	ll T;
	cin >> T;
	for (ll Ti = 1; Ti <= T; Ti++){
		ll N, M;
		scanf("%lld%lld", &N, &M);
		tree tr;
		for (ll i = 0; i < N; i++) split(), tr.insert();
		ll ans = 0;
		for (ll i = 0; i < M; i++) split(), ans += tr.count();
		printf("Case #%lld: %lld\n", Ti, ans);
	}return 0;
}

完整答案

结合一下即可。

C++
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define io ios::sync_with_stdio(0), cin.tie(), cout.tie()
const ll _p = 100;
vector<string> vec;
class node{
private:
	string father;
public:
	map<string, node*> sons;
	node(string _father): father(_father){}
	ll insert(ll x){
		if (x >= vec.size()) return 0;
		string dir = vec[x];
		ll cnt = 0;
		if (sons.find(dir) == sons.end()) sons[dir] = new node(dir), cnt = 1;
		return cnt + sons[dir]->insert(x + 1);
	}
};
class tree{
private:
	node* root;
public:
	tree(){root = new node("");}
	void insert(){
		node* tmp = root;
		for (string& dir : vec){
			if (tmp->sons.find(dir) == tmp->sons.end()) tmp->sons[dir] = new node(dir);
			tmp = tmp->sons[dir];
		}
	}
	ll count(){return root->insert(0);}
};
void split(){
	vec.clear();
	char p[_p];
	scanf("%s", p);
	stringstream ss(p);
	string s;
	while (getline(ss, s, '/')) if (!s.empty()) vec.push_back(s);
}
signed main(){
	ll T;
	cin >> T;
	for (ll Ti = 1; Ti <= T; Ti++){
		ll N, M;
		scanf("%lld%lld", &N, &M);
		tree tr;
		for (ll i = 0; i < N; i++) split(), tr.insert();
		ll ans = 0;
		for (ll i = 0; i < M; i++) split(), ans += tr.count();
		printf("Case #%lld: %lld\n", Ti, ans);
	}return 0;
}
原文