Skip to content

Commit bc2fd7d

Browse files
authored
Create 2020-A-D.cpp
1 parent 7a1eead commit bc2fd7d

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Diff for: kick-start/2020-A-D.cpp

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
struct Node{
6+
int son;
7+
int cnt;
8+
Node():son(-1),cnt(0){};
9+
};
10+
11+
12+
struct Trie{
13+
vector<vector<Node>> nodes;
14+
Trie(){
15+
nodes.push_back(vector<Node>(26));
16+
}
17+
int add_node(){
18+
nodes.push_back(vector<Node>(26));
19+
return nodes.size() -1;
20+
}
21+
void add_string(const string & str){
22+
int cur = 0;
23+
for(const auto e : str){
24+
int idx = e - 'A';
25+
auto &node = nodes[cur][idx];
26+
if (node.son == -1){// add new node
27+
node.son = add_node();
28+
}
29+
node.cnt ++;
30+
cur = node.son;
31+
}
32+
}
33+
int size(){
34+
return nodes.size();
35+
}
36+
};
37+
38+
pair<int,int> dfs(int u,int cnt, int dep,const Trie & trie,int K){
39+
int ans =0;
40+
int used = 0;
41+
for(const auto & e : trie.nodes[u]){
42+
if (e.son != -1 && e.cnt >=K){
43+
auto ret = dfs(e.son,e.cnt,dep +1, trie, K);
44+
ans += ret.first;
45+
used += ret.second;
46+
}
47+
}
48+
if ( cnt -used>=K){
49+
ans += (cnt - used)/K * dep;
50+
used += (cnt - used)/ K * K;
51+
}
52+
return make_pair(ans, used);
53+
}
54+
55+
void solve(){
56+
int N,K;
57+
cin >> N >> K;
58+
Trie trie;
59+
for(int i=0 ; i< N ; ++i)
60+
{
61+
string s;
62+
cin >> s;
63+
trie.add_string(s);
64+
}
65+
auto ans = dfs(0,N,0,trie,K);
66+
cout << ans.first << "\n";
67+
}
68+
69+
int main(){
70+
int T;
71+
cin >> T;
72+
73+
for(int t =1 ; t <= T ; ++ t){
74+
cout << "Case #"<<t<<": ";
75+
76+
solve();
77+
}
78+
return 0;
79+
}

0 commit comments

Comments
 (0)