-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathconstruct-string-with-minimum-cost.cpp
134 lines (120 loc) · 3.48 KB
/
construct-string-with-minimum-cost.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Time: O(n^2 + w * l)
// Space: O(t)
static const int INF = numeric_limits<int>::max();
// trie, dp
class Solution {
private:
class Trie {
public:
Trie() {
new_node();
}
void add(const string& w, int c) {
int curr = 0;
for (auto x : w) {
x -= 'a';
if (nodes_[curr][x] == -1) {
nodes_[curr][x] = new_node();
}
curr = nodes_[curr][x];
}
mns_[curr] = min(mns_[curr], c);
}
vector<pair<int, int>> query(int i, const string& t, vector<int>& dp) {
vector<pair<int, int>> result;
int curr = 0;
for (int j = i; j < size(t); ++j) {
const int x = t[j] - 'a';
if (nodes_[curr][x] == -1) {
break;
}
curr = nodes_[curr][x];
if (mns_[curr] != INF) {
dp[j + 1] = min(dp[j + 1], dp[i] + mns_[curr]);
}
}
return result;
}
private:
int new_node() {
nodes_.emplace_back(26, -1);
mns_.emplace_back(INF);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
vector<int> mns_;
};
public:
int minimumCost(string target, vector<string>& words, vector<int>& costs) {
Trie trie;
for (int i = 0; i < size(words); ++i) {
trie.add(words[i], costs[i]);
}
vector<int> dp(size(target) + 1, INF);
dp[0] = 0;
for (int i = 0; i < size(target); ++i) {
if (dp[i] == INF) {
continue;
}
trie.query(i, target, dp);
}
return dp.back() != INF ? dp.back() : -1;
}
};
// Time: O(n^2 + w * l)
// Space: O(t)
// trie, dp
class Solution2 {
private:
struct TrieNode {
int cost = INF;
unordered_map<char, TrieNode *> children;
TrieNode() {}
void add(const string& w, int c) {
auto* curr = this;
for (const auto& x : w) {
if (!curr->children[x]) {
curr->children[x] = new TrieNode;
}
curr = curr->children[x];
}
curr->cost = min(curr->cost, c);
}
void query(int i, const string& t, vector<int>& dp) {
auto* curr = this;
for (int j = i; j < size(t); ++j) {
const int x = t[j];
if (!curr->children.count(x)) {
break;
}
curr = curr->children[x];
if (curr->cost != INF) {
dp[j + 1] = min(dp[j + 1], dp[i] + curr->cost);
}
}
}
~TrieNode() {
for (auto& kv : children) {
if (kv.second) {
delete kv.second;
}
}
}
};
public:
int minimumCost(string target, vector<string>& words, vector<int>& costs) {
TrieNode trie;
for (int i = 0; i < size(words); ++i) {
trie.add(words[i], costs[i]);
}
vector<int> dp(size(target) + 1, INF);
dp[0] = 0;
for (int i = 0; i < size(target); ++i) {
if (dp[i] == INF) {
continue;
}
trie.query(i, target, dp);
}
return dp.back() != INF ? dp.back() : -1;
}
};