-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7271.cpp
More file actions
135 lines (108 loc) · 2.48 KB
/
7271.cpp
File metadata and controls
135 lines (108 loc) · 2.48 KB
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
// https://coderun.yandex.ru/problem/language-barier
// trie/prefix-tree + strings/prefix relation + bottom-up DFS greedy pairing + DSU-on-tree.
#include <bits/stdc++.h>
using namespace std;
typedef string str;
typedef long long ll;
typedef vector<int> vi;
typedef vector<pair<int,int>> vpii;
typedef vector<string> vs;
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)((x).size())
#define rep(i,a,b) for(int i=(a); i<(b); i++)
#define rsr(v,n) (v).reserve(n)
#define pb push_back
#define eb emplace_back
#define ppb pop_back
#define fi first
#define se second
#define ins insert
struct slv
{
struct nd
{ int nx[26]; vi id; nd() { memset(nx, -1, sizeof(nx)); } }; typedef vector<nd> vnd;
vnd t;
vpii ans;
void ins(const str& s, int k)
{
int u = 0;
for(char c : s)
{
int x = c - 'a';
if(t[u].nx[x] == -1)
{
t[u].nx[x] = sz(t);
t.eb();
}
u = t[u].nx[x];
}
t[u].id.pb(k);
}
vi dfs(int u)
{
vi buf;
rep(i,0,26)
{
int v = t[u].nx[i];
if(v == -1) continue;
vi tmp = dfs(v);
if(buf.empty())
{
buf = move(tmp);
}
else
{
if(sz(tmp) > sz(buf)) swap(buf, tmp);
buf.ins(buf.end(), tmp.begin(), tmp.end());
}
}
vi& loc = t[u].id;
while(!buf.empty() && !loc.empty())
{
int a = loc.back();
loc.ppb();
int b = buf.back();
buf.ppb();
ans.pb({a, b});
}
while(sz(loc) >= 2)
{
int a = loc.back();
loc.ppb();
int b = loc.back();
loc.ppb();
ans.pb({a, b});
}
if(!loc.empty()) buf.pb(loc.back());
return buf;
}
vpii run(int n, const vs& w)
{
(void)n;
t.clear();
ans.clear();
rsr(t, 500005);
t.eb();
rep(i,0,sz(w)) ins(w[i], i + 1);
dfs(0);
return ans;
}
};
vpii solve(int n, vs w)
{
slv s;
return s.run(n, w);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
if(!(cin >> n)) return 0;
vs w(2 * n);
rep(i,0,2 * n) cin >> w[i];
vpii ans = solve(n, w);
cout << sz(ans) << '\n';
for(auto &p : ans) cout << p.fi << ' ' << p.se << '\n';
return 0;
}