Official

C - Martial artist Editorial by en_translator


Consider a graph of \(N\) vertices in which there is an edge from every Vertex \(i\) \((1\leq i\leq N)\) to Vertex \(A_{i,j}\) \((1\leq j\leq K_i)\). Note that for every edge and the two vertices connected by the edge, the edge starts with the vertex with the larger index to that with the smaller index.

If one can travel on this graph from Vertex \(N\) to Vertex \(V\) \((1\leq V\leq N-1)\), then in order for him to learn Move \(N\), he must learn Move \(V\). This is why: take an arbitrary path from \(N\) to \(V\) on the graph, and denote the vertices on the path (including the endpoints) by \(u_1(=N), u_2, \ldots, u_m(=V)\) in order; then for each \(1\leq i\leq m-1\), before starting to learn Move \(u_i\), Move \(u_{i+1}\) must already be learned. Therefore, let \(S\) be the set of all vertices reachable from Vertex \(U\) (including \(U\) itself), and let \(V_1,V_2, \ldots, V_{\lvert S\rvert}\) be the elements of \(S\) in the increasing order, then it requires at least \(\displaystyle\sum_{i=1}^{\lvert S\rvert}T_{V_i}\) time to learn Move \(N\).

Conversely, we will show that he can practice Move \(V_i\) in the order of \(i=1,2,\ldots, \lvert S\rvert\). For any \(1\leq i\leq \lvert S\rvert\) and \(1\leq j\leq K_{V_i}\), on the graph we considered above, one can reach from Vertex \(N\) to vertex \(A_{V_i,j}\) via Vertex \(V_i\). Therefore, \(A_{V_i,j}\in S\), and since \(A_{V_i,j}<V_i\), it can be written as \(V_{i'}\) with some \(i'<i\). Therefore, at the beginning of learning Move \(V_i\), Move \(A_{V_i,j}\) is already learned, so it is proven that the Moves can be learned in the order described above.

Therefore, the answer is \(\displaystyle\sum_{i=1}^{\lvert S\rvert}T_{V_i}\), where \(S\) and \(V_1,V_2, \ldots, V_{\lvert S\rvert}\) are defined as above.

Since the number of edges in the graph above is \(M=\displaystyle\sum_{i=1}^{N} K_i\), one can enumerate the set of vertices that are reachable from Vertex \(N\) with BFS (Breadth-First Search) or DFS (Depth-First Search) in a total of \(O\left( N+\displaystyle\sum_{i=1}^{N} K_i \right) \) time. Therefore, the problem has been solved.

Sample code in C++:

#include <bits/stdc++.h>

using namespace std;
 
#define N 200100
#define MOD 998244353
#define ll long long
#define rep(i, n) for(int i = 0; i < n; ++i)

ll t[N];
int k[N];
vector<int>e[N];

bool used[N];

int main(void) {
	int n, x;
	ll ans = 0;
	rep(i, N)used[i] = false;

	cin >> n;
	rep(i, n) {
		cin >> t[i];
		cin >> k[i];
		rep(j, k[i]) {
			cin >> x;
			e[i].push_back(x - 1);
		}
	}

	used[n - 1] = true;
	for (int i = n - 1; i >= 0; i--) {
		if (used[i]) {
			ans += t[i];
			rep(j, k[i]) {
				used[e[i][j]] = true;
			}
		}
	}

	cout << ans << endl;

	return 0;
}

posted:
last update: