QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#863750 | #9716. Code a Trie | IllusionaryDominance | TL | 0ms | 3712kb | C++20 | 2.3kb | 2025-01-19 21:56:41 | 2025-01-19 21:56:47 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+5;
int ch[N][30], tot = 1;
int val[N];
bool cut[N];
bool ins(string s, int v)
{
int p = 1;
for (auto x : s)
{
if (ch[p][x-'a'] == 0) ch[p][x-'a'] = ++ tot;
p = ch[p][x-'a'];
}
if (val[p] != 0)
{
if (val[p] != v) return 0;
}
else val[p] = v;
return 1;
}
void dfs(int x)
{
int tmp = 0;
cut[x] = 1;
for (int i = 0; i < 26; ++i) if (ch[x][i])
{
dfs(ch[x][i]);
cut[x] &= cut[ch[x][i]];
if (val[ch[x][i]] != 0)
{
if (tmp != 0 && tmp != val[ch[x][i]]) tmp = -1;
else tmp = val[ch[x][i]];
}
}
if (cut[x] && tmp != -1 && (tmp == 0 || val[x] == 0 || val[x] == tmp))
{
if (tmp) val[x] = tmp;
}
else cut[x] = 0;
}
map<int, int> num;
int dfs2(int x)
{
int ans = 1;
if (val[x]) num[val[x]] ++;
if (cut[x]) return 1;
bool allcut = 1; int mxid = 0;
for (int i = 0; i < 26; ++i) if (ch[x][i]) allcut &= cut[ch[x][i]];
if (val[x])
{
for (int i = 0; i < 26; ++i) if (ch[x][i])
{
if (cut[ch[x][i]] && val[ch[x][i]] == val[x]) continue;
ans += dfs2(ch[x][i]);
}
}
else if (allcut)
{
--ans;
for (int i = 0; i < 26; ++i) if (ch[x][i]) num[val[ch[x][i]]]++, ans ++;
}
else
{
for (int i = 0; i < 26; ++i) if (ch[x][i])
{
ans += dfs2(ch[x][i]);
}
}
return ans;
}
void init()
{
for (int i = 0; i <= tot; ++i)
{
for (int j = 0; j < 30; ++j) ch[i][j] = 0;
val[i] = 0, cut[i] = 0;
}
num.clear();
tot = 1;
}
void solve()
{
int n; cin >> n;
for (int i = 0; i < n; ++i)
{
string x; int y;
cin >> x >> y;
if (!ins(x, y)) { cout << "-1\n"; return; }
}
dfs(1);
int ans = dfs2(1);
bool fl = 1;
for (auto [x, y] : num) if (y > 1) fl = 0;
if (fl) cout << ans << "\n";
else cout << "-1\n";
init();
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T;
cin >> T;
for (int i = 1; i <= T; i ++)
{
cout << "Case #" << i << ": ";
solve();
}
}
详细
Test #1:
score: 100
Accepted
time: 0ms
memory: 3712kb
input:
6 2 aa 1 a 2 1 a 1 3 aa 1 ab 1 ac 1 2 aa 1 ac 2 3 aaa 1 ac 1 aa 3 3 aa 1 ac 1 a 3
output:
Case #1: 3 Case #2: 1 Case #3: 1 Case #4: 3 Case #5: -1 Case #6: -1
result:
ok 6 lines
Test #2:
score: -100
Time Limit Exceeded
input:
873 1 sgaswyo 17974065 1 s 17974065 1 naa 17974065 3 m 17974065 yimyi 864021569 m 421852697 4 sawa 613320183 auqacuy 147847601 u 58500993 aesc 461860441 1 x 613320183 3 su 613320183 g 147847601 a 750104225 3 saic 589460253 i 147847601 s 3910501 1 ioqxgke 812288287 5 a 878568205 a 147847601 c 1474279...