AtCoder Beginner Contest 374

AtCoder Beginner Contest 374

G - Only One Product Name

对于每个出现的字符串 $s$ ,我们从 $s[0]$ 连一条向 $s[1]$ 的边,这样问题转化为使用最小的路径覆盖所有的边。我们把边转化成点,这样就是经典的最小路径覆盖问题。

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
135
136
137
138
139
140
141
142
143
144
145
#include <bits/stdc++.h>

using i64 = long long;

// 边双连通分量

struct Edge {
int to;
int id;
operator int() const
{
return to;
}
};

struct SCC {
int n;
std::vector<std::vector<Edge>> g;
std::vector<int> stk;
std::vector<int> in, out, low, id;
int ts, cnt;

SCC(const std::vector<std::vector<Edge>> &g) : n(int(g.size()) - 1), g(g)
{
in.assign(n + 1, 0);
out.assign(n + 1, 0);
low.assign(n + 1, 0);
id.assign(n + 1, 0);
stk.clear();
ts = cnt = 0;
for (int i = 1; i <= n; i++) {
if (in[i] == 0) {
dfs(i);
}
}
}

void dfs(int x)
{
in[x] = low[x] = ++ts;
stk.push_back(x);
for (auto y : g[x]) {
if (in[y] == 0) {
dfs(y);
low[x] = std::min(low[x], low[y]);
} else if (id[y] == 0) {
low[x] = std::min(low[x], in[y]);
}
}
if (in[x] == low[x]) {
cnt++;
int y;
do {
y = stk.back();
id[y] = cnt;
stk.pop_back();
} while (y != x);
}
out[x] = ts;
}
};

void solve()
{
int n;
std::cin >> n;
std::vector<std::string> s(n + 1);
std::vector<std::vector<Edge>> g(n + 1);

for (int i = 1; i <= n; i++) {
std::cin >> s[i];
}

for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (s[i][1] == s[j][0]) {
g[i].push_back({j, 0});
}
}
}

SCC scc(g);
std::vector<std::vector<int>> d(n + 1, std::vector<int>(n + 1));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (s[i][1] == s[j][0]) {
d[scc.id[i]][scc.id[j]] = 1;
}
}
}

n = scc.cnt;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
if (d[i][k] && d[k][j]) {
d[i][j] = 1;
}
}
}
}
std::vector<std::vector<int>> adj(scc.cnt + 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (d[i][j] && i != j) {
adj[i].push_back(j);
}
}
}

std::vector<int> match(n + 1);
int ans = n;
for (int i = 1; i <= n; i++) {
std::vector<int> st(n + 1);
auto find = [&](auto self, int x) -> int {
for (auto v : adj[x]) {
if (!st[v]) {
st[v] = true;
if (match[v] == 0 || self(self, match[v])) {
match[v] = x;
return 1;
}
}
}
return 0;
};
ans -= find(find, i);
}
std::cout << ans << "\n";
}

int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);

// freopen("in.txt", "r", stdin);

int t = 1;
// std::cin >> t;
while (t--)
solve();

return 0;
}

AtCoder Beginner Contest 374
http://example.com/2024/10/06/AtCoder-Beginner-Contes-374/
作者
muxingchengfeng
发布于
2024年10月6日
许可协议