1+ /* *
2+ * @file 108199C.cpp
3+ * @author Macesuted ([email protected] ) 4+ * @date 2025-05-06
5+ *
6+ * @copyright Copyright (c) 2025
7+ *
8+ */
9+
10+ #include < bits/stdc++.h>
11+ using namespace std ;
12+
13+ #define endl ' \n '
14+
15+ #define maxn 100005
16+
17+ using pii = pair<int , int >;
18+
19+ unordered_set<int > graph[maxn];
20+ vector<int > ngraph[maxn];
21+ set<pii> avai[maxn];
22+ int ans[maxn], dist[maxn], pre [maxn];
23+ bool lck[maxn];
24+
25+ void solve (void ) {
26+ int n;
27+ cin >> n;
28+ for (int i = 1 ; i <= n; i++) avai[n + i].emplace (1 , n);
29+ for (int i = 1 , m, x; i <= n; i++) {
30+ cin >> m;
31+ while (m--) {
32+ cin >> x;
33+ graph[i].insert (n + x);
34+
35+ auto p = --avai[n + x].lower_bound ({i + 1 , 0 });
36+ auto [l, r] = *p;
37+ avai[n + x].erase (p);
38+ if (l < i) avai[n + x].emplace (l, i - 1 );
39+ if (i < r) avai[n + x].emplace (i + 1 , r);
40+ }
41+ }
42+
43+ auto avaiLef = [&](int y) -> int {
44+ for (auto [l, r] : avai[y])
45+ for (int x = l; x <= r; x++)
46+ if (ans[x] && !lck[ans[x]]) return x;
47+ return 0 ;
48+ };
49+
50+ unordered_set<int > rig;
51+ for (int i = 1 ; i <= n; i++) rig.insert (n + i);
52+ for (int x = 1 ; x <= n; x++) {
53+ for (auto y : rig)
54+ if (!graph[x].count (y)) {
55+ ans[x] = y, ans[y] = x, rig.erase (y);
56+ break ;
57+ }
58+ if (ans[x]) continue ;
59+
60+ for (auto y : graph[x]) lck[y] = true ;
61+
62+ for (auto i : graph[x])
63+ for (auto j : graph[x])
64+ if (ans[i] && i != j && !graph[ans[i]].count (j)) ngraph[i].push_back (j);
65+
66+ for (auto y2 : graph[x]) {
67+ int x1 = avaiLef (y2);
68+ if (!x1) continue ;
69+ int y1 = ans[x1];
70+
71+ queue<int > que;
72+ que.push (y2);
73+ for (auto y : graph[x]) dist[y] = INT_MAX;
74+ dist[y2] = pre [y2] = 0 ;
75+ while (!que.empty ()) {
76+ int p = que.front ();
77+ que.pop ();
78+ for (auto q : ngraph[p])
79+ if (dist[q] > dist[p] + 1 ) dist[q] = dist[p] + 1 , pre [q] = p, que.push (q);
80+ }
81+
82+ int y = 0 ;
83+ for (auto ty : graph[x])
84+ if (!ans[ty] && dist[ty] != INT_MAX) y = ty;
85+ if (!y) continue ;
86+
87+ vector<int > lnk;
88+ while (y) lnk.push_back (y), y = pre [y];
89+ lnk.push_back (y1);
90+ reverse (lnk.begin (), lnk.end ());
91+ for (int i = lnk.size () - 1 ; i; i--) {
92+ int x = ans[lnk[i - 1 ]], y = lnk[i];
93+ ans[x] = y, ans[y] = x;
94+ }
95+ ans[x] = lnk[0 ], ans[lnk[0 ]] = x;
96+ rig.erase (lnk.back ());
97+
98+ break ;
99+ }
100+
101+ if (!ans[x]) return cout << -1 << endl, void ();
102+
103+ for (auto y : graph[x]) lck[y] = false , ngraph[y].clear ();
104+ }
105+
106+ for (int i = 1 ; i <= n; i++) cout << ans[i] - n << ' ' ;
107+ cout << endl;
108+
109+ return ;
110+ }
111+
112+ int main () {
113+ ios::sync_with_stdio (false ), cin.tie (nullptr );
114+
115+ int _ = 1 ;
116+ while (_--) solve ();
117+
118+ return 0 ;
119+ }
0 commit comments