input
stringlengths
29
13k
output
stringlengths
9
73.4k
There is a city that can be represented as a square grid with corner points in (0, 0) and (10^6, 10^6). The city has n vertical and m horizontal streets that goes across the whole city, i. e. the i-th vertical streets goes from (x_i, 0) to (x_i, 10^6) and the j-th horizontal street goes from (0, y_j) to (10^6, y_j). All streets are bidirectional. Borders of the city are streets as well. There are k persons staying on the streets: the p-th person at point (x_p, y_p) (so either x_p equal to some x_i or y_p equal to some y_j, or both). Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them. Calculate the number of inconvenient pairs of persons (pairs (x, y) and (y, x) are the same pair). Let's recall that Manhattan distance between points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains three integers n, m and k (2 ≀ n, m ≀ 2 β‹… 10^5; 2 ≀ k ≀ 3 β‹… 10^5) β€” the number of vertical and horizontal streets and the number of persons. The second line of each test case contains n integers x_1, x_2, ..., x_n (0 = x_1 < x_2 < ... < x_{n - 1} < x_n = 10^6) β€” the x-coordinates of vertical streets. The third line contains m integers y_1, y_2, ..., y_m (0 = y_1 < y_2 < ... < y_{m - 1} < y_m = 10^6) β€” the y-coordinates of horizontal streets. Next k lines contains description of people. The p-th line contains two integers x_p and y_p (0 ≀ x_p, y_p ≀ 10^6; x_p ∈ \\{x_1, ..., x_n\} or y_p ∈ \\{y_1, ..., y_m\}) β€” the coordinates of the p-th person. All points are distinct. It guaranteed that sum of n doesn't exceed 2 β‹… 10^5, sum of m doesn't exceed 2 β‹… 10^5 and sum of k doesn't exceed 3 β‹… 10^5. Output For each test case, print the number of inconvenient pairs. Example Input 2 2 2 4 0 1000000 0 1000000 1 0 1000000 1 999999 1000000 0 999999 5 4 9 0 1 2 6 1000000 0 4 8 1000000 4 4 2 5 2 2 6 3 1000000 1 3 8 5 8 8 8 6 8 Output 2 5 Note The second test case is pictured below: <image> For example, points 3 and 4 form an inconvenient pair, since the shortest path between them (shown red and equal to 7) is greater than its Manhattan distance (equal to 5). Points 3 and 5 also form an inconvenient pair: the shortest path equal to 1000001 (shown green) is greater than the Manhattan distance equal to 999999. But points 5 and 9 don't form an inconvenient pair, since the shortest path (shown purple) is equal to its Manhattan distance.
#include <bits/stdc++.h> using namespace std; long long mod = 998244353; const int N = 3e5 + 5; const int M = 20 * N; void Evlos() { int n, m, k; cin >> n >> m >> k; vector<int> x(n), y(m); for (int i = 0; i < n; i++) { cin >> x[i]; } for (int i = 0; i < m; i++) { cin >> y[i]; } long long ans = 0; vector<vector<int>> a(m + 5), b(n + 5); for (int i = 0; i < k; i++) { int p, q; cin >> p >> q; int it = lower_bound(x.begin(), x.end(), p) - x.begin(); int jt = lower_bound(y.begin(), y.end(), q) - y.begin(); if (x[it] == p && y[jt] == q) continue; if (x[it] == p) { a[jt].push_back(it); } else { b[it].push_back(jt); } } for (int i = 0; i < n; i++) { sort(b[i].begin(), b[i].end()); for (int j = 0; j < b[i].size();) { int l = j; while (l < b[i].size() && b[i][l] == b[i][j]) l++; ans += 1LL * (l - j) * (b[i].size() - l); j = l; } } for (int i = 0; i < m; i++) { sort(a[i].begin(), a[i].end()); for (int j = 0; j < a[i].size();) { int l = j; while (l < a[i].size() && a[i][l] == a[i][j]) l++; ans += 1LL * (l - j) * (a[i].size() - l); j = l; } } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cerr.tie(0); int tt = 1; cin >> tt; while (tt--) Evlos(); return 0; }
2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains. After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular: * the winner of the tournament gets place 1; * the team eliminated in the finals gets place 2; * both teams eliminated in the semifinals get place 3; * all teams eliminated in the quarterfinals get place 5; * all teams eliminated in the 1/8 finals get place 9, and so on. For example, this picture describes one of the possible ways the tournament can go with k = 3, and the resulting places of the teams: <image> After a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let p_i be the place of the i-th team in the tournament. The hash value of the tournament h is calculated as h = (βˆ‘ _{i=1}^{2^k} i β‹… A^{p_i}) mod 998244353, where A is some given integer. Unfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of k, A and h. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all. Input The only line contains three integers k, A and h (1 ≀ k ≀ 5; 100 ≀ A ≀ 10^8; 0 ≀ h ≀ 998244352). Output If it is impossible to find any placing of the teams that is consistent with the data you have, print one integer -1. Otherwise, print 2^k integers, where i-th integer should be equal to p_i (the place of the i-th team). Note that your answer should be consistent with one of the possible ways the tournament could go, and note that the initial structure of the tournament is fixed (for example, teams 1 and 2 always play in the first phase of the tournament against each other). If there are multiple ways to restore the places of the teams which are consistent with the data you have, print any of them. Examples Input 3 1337 75275197 Output 5 3 5 2 1 5 5 3 Input 2 100 5040100 Output 1 3 3 2 Input 2 100 7020100 Output -1 Note The tournament for the first example is described in the statement. For the third example, the placing [1, 2, 3, 3] (team 1 gets place 1, team 2 gets place 2, teams 3 and 4 get place 3) could result in a hash value of 7020100 with A = 100, but no tournament can result in such placing since teams 1 and 2 play against each other in the semifinals, so they cannot get two first places.
import sys def pr(x): sys.stdout.write(str(x)+'\n') def inp(): return sys.stdin.readline() M = 998244353 k, a, h = [int(i) for i in inp().split()] pp = [[],[2],[3,2],[5,3,2],[9,5,3,2],[17,9,5,3,2]] pa = [(a**i)%M for i in pp[k]] rgs = [[], [[1,3]], [[4,7], [1,5]], [[16, 21], [6,13], [1,9]], [[64, 73], [28, 41], [10, 25], [1,17]], [[256, 273], [120, 145], [52, 81], [18, 49], [1,33]]] rg = rgs[k] xa = {} for i in range(1, (1<<k)+1): xa[i*a%M] = i r = [0]*(k+1) def dfs(n, num): if n == k: x = (h + M - num) % M # print(r, x, x%a) if x in xa: r[n] = xa[x] # print(r) if sum(r) == sum(range(1,(1<<k)+1)): return True else: for i in range(rg[n][0], rg[n][1]): r[n] = i if dfs(n+1, (num+i*pa[n])%M): return True return False if not dfs(0, 0): pr(-1) sys.exit() if sum(r) != sum(range(1,(1<<k)+1)): # pr(r) pr(-1) sys.exit() res = [pp[k][0]]*(1<<k) res[r[-1]-1] = 1 res[r[-2]-1] = 2 if (r[-1]-1) // 1<<(k-1) == (r[-2]-1) // 1<<(k-1): pr(-1) sys.exit() for i in range(k-2, 0, -1): t = [1]*(1<<(k-i)) for j in range(1<<k): if res[j] != pp[k][0]: t[j // (1<<i)] = 0 r[i] -= sum((j*1<<i)+1 for j in range(len(t)) if t[j]) for j in range(len(t)): if t[j]: x = min(r[i], (1<<i)-1) r[i] -= x res[(j*(1<<i))+x] = pp[k][i] if r[i]: pr(-1) sys.exit() print(' '.join(str(i) for i in res))
You are given a simple undirected graph with n vertices, n is even. You are going to write a letter on each vertex. Each letter should be one of the first k letters of the Latin alphabet. A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order. A string of length n is good if: * each letter is one of the first k lowercase Latin letters; * if you write the i-th letter of the string on the i-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph. Note that the path doesn't necesserily go through the vertices in order 1, 2, ..., n. Count the number of good strings. Input The first line contains three integers n, m and k (2 ≀ n ≀ 12; n is even; 0 ≀ m ≀ (n β‹… (n-1))/(2); 1 ≀ k ≀ 12) β€” the number of vertices in the graph, the number of edges in the graph and the number of first letters of the Latin alphabet that can be used. Each of the next m lines contains two integers v and u (1 ≀ v, u ≀ n; v β‰  u) β€” the edges of the graph. The graph doesn't contain multiple edges and self-loops. Output Print a single integer β€” number of good strings. Examples Input 4 3 3 1 2 2 3 3 4 Output 9 Input 4 6 3 1 2 1 3 1 4 2 3 2 4 3 4 Output 21 Input 12 19 12 1 3 2 6 3 6 3 7 4 8 8 5 8 7 9 4 5 9 10 1 10 4 10 6 9 10 11 1 5 11 7 11 12 2 12 5 12 11 Output 456165084
#include <bits/stdc++.h> using namespace std; int rev[1 << 20]; int dp[1 << 13][13][13]; int visit[1 << 13][13][13]; bool visit2[1 << 20]; int maps[13], c[13]; int a[13][13]; int n, m, r; long long ans = 0; int stage; vector<pair<int, int> > v[1 << 13][13][13]; vector<int> edges[1 << 20]; long long A(int r, int g) { int ans = 1; for (int i = 1; i <= g; i++) ans *= (r - i + 1); return ans; } bool vis[1 << 20]; bool dfs2(int x, int y, int state) { if (state == (1 << n) - 1) { visit[state][x][y] = stage; return dp[state][x][y] = true; } if (visit[state][x][y] == stage) return false; for (int i = 0; i < v[state][x][y].size(); i++) { int p = v[state][x][y][i].first; int q = v[state][x][y][i].second; if (maps[p] == maps[q] && dfs2(p, q, state | (1 << p) | (1 << q))) { visit[state][x][y] = stage; return dp[state][x][y] = true; } } visit[state][x][y] = stage; return dp[state][x][y] = false; } bool check() { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i][j] && maps[i] == maps[j] && dfs2(i, j, (1 << i) | (1 << j))) return true; return false; } int flag; unordered_map<int, int> mp; int get_state(int a[]) { int state = 0; for (int i = 0; i < n; i++) state = 6 * state + a[i] - 1; return state; } void decode_state(int maps[], int state) { for (int i = n - 1; i >= 0; i--) { maps[i] = state % 6 + 1; state /= 6; } } void dfs(int pos, int group) { stage++; if (group > min(6, r) || pos + flag > n) return; if (pos == n) { int id = get_state(maps); int sz = mp.size(); mp[id] = sz; rev[sz] = id; if ((group == r || group * 2 == n) && check()) { vis[sz] = true; } return; } c[group + 1]++; flag++; maps[pos] = group + 1; dfs(pos + 1, group + 1); flag--; c[group + 1]--; for (int i = 1; i <= group; i++) { c[i]++; if (c[i] & 1) flag++; else flag--; maps[pos] = i; dfs(pos + 1, group); if (c[i] & 1) flag--; else flag++; c[i]--; } } int main() { scanf("%d%d%d", &n, &m, &r); while (m--) { int x, y; scanf("%d%d", &x, &y); x--, y--; a[x][y] = a[y][x] = 1; } for (int i = 0; i < (1 << n); i++) { int cnt = 0; for (int j = 0; j < n; j++) if (i & (1 << j)) cnt++; if (cnt & 1) continue; for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) if ((i & (1 << j)) && (i & (1 << k))) for (int p = 0; p < n; p++) for (int q = 0; q < n; q++) if (a[j][p] && a[k][q] && p != q && !(i & (1 << p)) && !(i & (1 << q))) v[i][j][k].push_back(make_pair(p, q)); } dfs(0, 0); for (unordered_map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) { decode_state(maps, it->first); int maps2[13]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if (maps[i] != maps[j]) { for (int k = 0; k < n; k++) maps2[k] = maps[k]; int id = min(maps[i], maps[j]); int id2 = max(maps[i], maps[j]); for (int k = 0; k < n; k++) if (maps[j] == maps[k]) maps2[k] = id; for (int k = 0; k < n; k++) if (maps2[k] > id2) maps2[k]--; int x = get_state(maps2); edges[it->second].push_back(mp[x]); } } } queue<int> q; for (int i = 0; i < mp.size(); i++) { if (vis[i]) q.push(i), visit2[i] = true; } while (!q.empty()) { int u = q.front(); q.pop(); decode_state(maps, rev[u]); int mx = 0; for (int i = 0; i < n; i++) mx = max(mx, maps[i]); ans += A(r, mx); for (int i = 0; i < edges[u].size(); i++) { int x = edges[u][i]; if (visit2[x]) continue; q.push(x); visit2[x] = true; } } cout << ans << endl; return 0; }
You are given a sequence a of length n consisting of 0s and 1s. You can perform the following operation on this sequence: * Pick an index i from 1 to n-2 (inclusive). * Change all of a_{i}, a_{i+1}, a_{i+2} to a_{i} βŠ• a_{i+1} βŠ• a_{i+2} simultaneously, where βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) Find a sequence of at most n operations that changes all elements of a to 0s or report that it's impossible. We can prove that if there exists a sequence of operations of any length that changes all elements of a to 0s, then there is also such a sequence of length not greater than n. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). The first line of each test case contains a single integer n (3 ≀ n ≀ 2β‹…10^5) β€” the length of a. The second line of each test case contains n integers a_1, a_2, …, a_n (a_i = 0 or a_i = 1) β€” elements of a. It is guaranteed that the sum of n over all test cases does not exceed 2β‹…10^5. Output For each test case, do the following: * if there is no way of making all the elements of a equal to 0 after performing the above operation some number of times, print "NO". * otherwise, in the first line print "YES", in the second line print k (0 ≀ k ≀ n) β€” the number of operations that you want to perform on a, and in the third line print a sequence b_1, b_2, ..., b_k (1 ≀ b_i ≀ n - 2) β€” the indices on which the operation should be applied. If there are multiple solutions, you may print any. Example Input 3 3 0 0 0 5 1 1 1 1 0 4 1 0 0 1 Output YES 0 YES 2 3 1 NO Note In the first example, the sequence contains only 0s so we don't need to change anything. In the second example, we can transform [1, 1, 1, 1, 0] to [1, 1, 0, 0, 0] and then to [0, 0, 0, 0, 0] by performing the operation on the third element of a and then on the first element of a. In the third example, no matter whether we first perform the operation on the first or on the second element of a we will get [1, 1, 1, 1], which cannot be transformed to [0, 0, 0, 0].
#include <bits/stdc++.h> #pragma GCC optimize("O2,unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,mmx,avx,avx2") using namespace std; const long double PI = 3.14159265358979323846; const long double E = 2.71828182845904523536; const long long LINF = (long long)2e18; const int INF = (1 << 30); const long double eps = 1e-10; const int MAXN = 2e5 + 5; int a[MAXN]; int b[MAXN]; int l[MAXN]; int s[MAXN], f[MAXN]; int inq[MAXN]; int n; vector<int> ans; int idx = 1; bool remove(int s, int f, vector<int>& skip) { if (s == 0 && f == n - 1 && !skip.size()) { return false; } int tct = 0; for (int i = s; i <= f; i++) { b[i] = 1; tct++; } idx++; queue<int> q; if (s != 0) { q.push(s - 1); inq[s - 1] = idx; } if (f != n - 1) { q.push(f - 1); inq[f - 1] = idx; } for (int i : skip) { if (inq[i - 1] != idx) { q.push(i - 1); inq[i - 1] = idx; } b[i] = 0; tct--; } for (int i = s; i <= f; i++) { if (a[i] == 0 && b[i] != 0) { a[i + 1] = 1; ans.push_back(i); } } while (q.size()) { int k = q.front(); q.pop(); int ct = 0; if (b[k]) { ct++; } if (b[k + 1]) { ct++; } if (b[k + 2]) { ct++; } if (ct != 2) { continue; } tct -= 2; b[k] = 0; b[k + 1] = 0; b[k + 2] = 0; ans.push_back(k + 1); if (inq[k - 1] != idx && k - 1 >= 0 && k - 1 <= n - 1) { inq[k - 1] = idx; q.push(k - 1); }; if (inq[k + 1] != idx && k + 1 >= 0 && k + 1 <= n - 1) { inq[k + 1] = idx; q.push(k + 1); }; if (inq[k - 2] != idx && k - 2 >= 0 && k - 2 <= n - 1) { inq[k - 2] = idx; q.push(k - 2); }; if (inq[k + 2] != idx && k + 2 >= 0 && k + 2 <= n - 1) { inq[k + 2] = idx; q.push(k + 2); }; } return !tct; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); std::cout << std::fixed << std::setprecision(20); int qr; for (cin >> qr; qr; qr--) { cin >> n; ans.clear(); int ct = 0; bool ok = 0; for (int i = 0; i < n; i++) { cin >> a[i]; ct ^= a[i]; ok |= !a[i]; } if (ct || !ok) { cout << "NO\n"; continue; } a[n] = 0; int ptr = 0; for (int i = 0; i < n;) { int j = i; l[ptr] = 0; s[ptr] = i; while (j < n && a[j] == a[i]) { l[ptr]++; j++; } f[ptr] = j - 1; i = j; ptr++; } for (int i = 0; i < ptr;) { if (!a[s[i]]) { i++; continue; } int temp = l[i]; vector<int> skip; int j = i; while (temp & 1) { int k0 = j + 1; temp += l[k0] - (l[k0] & 1); if (l[k0] & 1) { skip.push_back(f[k0]); } int k1 = j + 2; if (k1 == ptr || k0 == ptr) { cout << "NO\n"; goto done; } temp += l[k1]; j += 2; } if (!remove(s[i], f[j], skip)) { cout << "NO\n"; goto done; } i = j + 1; } cout << "YES\n"; cout << ans.size() << '\n'; for (int i : ans) { cout << i << ' '; } cout << '\n'; done:; } }
You are given a 1 by n pixel image. The i-th pixel of the image has color a_i. For each color, the number of pixels of that color is at most 20. You can perform the following operation, which works like the bucket tool in paint programs, on this image: * pick a color β€” an integer from 1 to n; * choose a pixel in the image; * for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^3). The first line of each test case contains a single integer n (1 ≀ n ≀ 3β‹…10^3) β€” the number of pixels in the image. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the colors of the pixels in the image. Note: for each color, the number of pixels of that color is at most 20. It is guaranteed that the sum of n over all test cases does not exceed 3β‹…10^3. Output For each test case, print one integer: the minimum number of operations needed to make all the pixels in the image have the same color. Example Input 3 5 1 2 3 2 1 4 1 1 2 2 5 1 2 1 4 2 Output 2 1 3 Note In the first example, the optimal solution is to apply the operation on the third pixel changing its color to 2 and then to apply the operation on any pixel that has color 2 changing its color and the color of all pixels connected to it to 1. The sequence of operations is then: [1, 2, 3, 2, 1] β†’ [1, 2, 2, 2, 1] β†’ [1, 1, 1, 1, 1]. In the second example, we can either change the 1s to 2s in one operation or change the 2s to 1s also in one operation. In the third example, one possible way to make all the pixels have the same color is to apply the operation on the first, third and the fourth pixel each time changing its color to 2.
#include <bits/stdc++.h> using namespace std; const int maxn = 3005; int T, n; int a[maxn], dp[maxn][maxn], pos[maxn]; vector<int> vec[maxn]; int calc(int l, int r) { if (l > r) return 0; int &ret = dp[l][r]; if (ret >= 0) return ret; ret = calc(l, r - 1); for (int i = pos[r] - 1; i >= 0; i--) { int p = vec[a[r]][i]; if (p < l) break; ret = max(ret, calc(l, p) + calc(p + 1, r - 1) + 1); } return ret; } int main() { scanf("%d", &T); while (T--) { scanf("%d", &n); for (int i = 1; i <= n; i++) vec[i].clear(); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); pos[i] = int(vec[a[i]].size()); vec[a[i]].push_back(i); } for (int l = 1; l <= n; l++) for (int r = l; r <= n; r++) dp[l][r] = -1; printf("%d\n", n - calc(1, n) - 1); } return 0; }
There are currently n hot topics numbered from 0 to n-1 at your local bridge club and 2^n players numbered from 0 to 2^n-1. Each player holds a different set of views on those n topics, more specifically, the i-th player holds a positive view on the j-th topic if i\ \&\ 2^j > 0, and a negative view otherwise. Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). You are going to organize a bridge tournament capable of accommodating at most k pairs of players (bridge is played in teams of two people). You can select teams arbitrarily while each player is in at most one team, but there is one catch: two players cannot be in the same pair if they disagree on 2 or more of those n topics, as they would argue too much during the play. You know that the i-th player will pay you a_i dollars if they play in this tournament. Compute the maximum amount of money that you can earn if you pair the players in your club optimally. Input The first line contains two integers n, k (1 ≀ n ≀ 20, 1 ≀ k ≀ 200) β€” the number of hot topics and the number of pairs of players that your tournament can accommodate. The second line contains 2^n integers a_0, a_1, ..., a_{2^n-1} (0 ≀ a_i ≀ 10^6) β€” the amounts of money that the players will pay to play in the tournament. Output Print one integer: the maximum amount of money that you can earn if you pair the players in your club optimally under the above conditions. Examples Input 3 1 8 3 5 7 1 10 3 2 Output 13 Input 2 3 7 4 5 7 Output 23 Input 3 2 1 9 1 5 7 8 1 1 Output 29 Note In the first example, the best we can do is to pair together the 0-th player and the 2-nd player resulting in earnings of 8 + 5 = 13 dollars. Although pairing the 0-th player with the 5-th player would give us 8 + 10 = 18 dollars, we cannot do this because those two players disagree on 2 of the 3 hot topics. In the second example, we can pair the 0-th player with the 1-st player and pair the 2-nd player with the 3-rd player resulting in earnings of 7 + 4 + 5 + 7 = 23 dollars.
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; const long long mod = 1e9 + 7; inline long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); } inline long long q_pow(long long a, long long x = mod - 2) { long long ans = 1, tmp = a; while (x) { if (x & 1) (ans *= tmp) %= mod; (tmp *= tmp) %= mod; x >>= 1; } return ans; } template <typename T> inline void re(T& N) { int f = 1; char c; while ((c = getchar()) < '0' || c > '9') if (c == '-') f = -1; N = c - '0'; while ((c = getchar()) >= '0' && c <= '9') N = N * 10 + c - '0'; N *= f; } template <class T, class... T_> inline void re(T& x, T_&... y) { re(x), re(y...); } int m, n, t = 1, st, en; template <class T> struct MCMF { struct edge { int v; T cap, cost; edge() {} edge(int v = 0, T cap = 0, T cost = 0) : v(v), cap(cap), cost(cost) {} }; int m, n, st, en; T cost, flow, inf = typeid(T) == typeid(int) ? 1e9 : 1e18; vector<edge> edges; vector<vector<int> > G; vector<int> fa, vis; vector<T> dis, lim; void init(int _n) { flow = cost = 0; G.assign(n + 1, vector<int>()); dis.assign(n + 1, inf); lim.assign(n + 1, 0); fa.assign(n + 1, 0); vis.assign(n + 1, 0); edges.clear(); lim[st] = inf; } void build(int _n) { n = _n; st = n - 1; en = n; init(n); } void build(int _n, int _st, int _en) { n = _n; st = _st; en = _en; init(n); } void add(int u, int v, T cap, T cost) { if (u == v) return; edges.emplace_back(v, cap, cost); edges.emplace_back(u, 0, -cost); m = edges.size(); G[u].push_back(m - 2); G[v].push_back(m - 1); } int spfa() { fill(dis.begin(), dis.end(), inf); queue<int> q; q.push(st); dis[st] = 0; while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for (int i = 0; i < G[u].size(); i++) { edge& e = edges[G[u][i]]; if (dis[e.v] > dis[u] + e.cost && e.cap) { dis[e.v] = dis[u] + e.cost; fa[e.v] = G[u][i]; lim[e.v] = min(lim[u], e.cap); if (!vis[e.v]) q.push(e.v), vis[e.v] = 1; } } } return dis[en] != inf; } void find_path() { int u = en; T _flow = lim[en]; while (u != st) { edge& e = edges[fa[u]]; edge& _e = edges[fa[u] ^ 1]; e.cap -= _flow; _e.cap += _flow; u = _e.v; } flow += _flow; cost += _flow * dis[en]; } T get() { while (spfa()) find_path(); return cost; } }; int a[N << 1]; vector<pair<int, int> > bin[N << 1]; int main() { re(n, m); for (int i = 0; i < 1 << n; i++) re(a[i]); for (int i = 0; i < 1 << n; i++) if (__builtin_parity(i)) { for (int j = 0; j < n; j++) { int to = i ^ (1 << j); bin[a[i] + a[to]].push_back({i, to}); } } int lef = (2 * n - 1) * (m - 1) + 1; vector<pair<int, int> > edges; vector<int> pnts; for (int i = 2e6; i >= 0 && lef; i--) for (auto j : bin[i]) { pnts.push_back(j.first); pnts.push_back(j.second); edges.push_back(j); if (!(--lef)) break; } sort(pnts.begin(), pnts.end()); pnts.erase(unique(pnts.begin(), pnts.end()), pnts.end()); MCMF<long long> f; f.build(pnts.size() + 10); f.add(f.st, f.st - 1, m, 0); for (int i : pnts) { int pos = lower_bound(pnts.begin(), pnts.end(), i) - pnts.begin() + 1; if (__builtin_parity(i)) f.add(f.st - 1, pos, 1, 0); else f.add(pos, f.en, 1, 0); } for (pair<int, int> i : edges) { int posl = lower_bound(pnts.begin(), pnts.end(), i.first) - pnts.begin() + 1; int posr = lower_bound(pnts.begin(), pnts.end(), i.second) - pnts.begin() + 1; f.add(posl, posr, 1, -(a[i.first] + a[i.second])); } printf("%lld\n", -f.get()); }
You are given a strictly convex polygon with n vertices. You will make k cuts that meet the following conditions: * each cut is a segment that connects two different nonadjacent vertices; * two cuts can intersect only at vertices of the polygon. Your task is to maximize the area of the smallest region that will be formed by the polygon and those k cuts. Input The first line contains two integers n, k (3 ≀ n ≀ 200, 0 ≀ k ≀ n-3). The following n lines describe vertices of the polygon in anticlockwise direction. The i-th line contains two integers x_i, y_i (|x_i|, |y_i| ≀ 10^8) β€” the coordinates of the i-th vertex. It is guaranteed that the polygon is convex and that no two adjacent sides are parallel. Output Print one integer: the maximum possible area of the smallest region after making k cuts multiplied by 2. Examples Input 8 4 -2 -4 2 -2 4 2 1 5 0 5 -4 4 -5 0 -5 -1 Output 11 Input 6 3 2 -2 2 -1 1 2 0 2 -2 1 -1 0 Output 3 Note In the first example, it's optimal to make cuts between the following pairs of vertices: * (-2, -4) and (4, 2), * (-2, -4) and (1, 5), * (-5, -1) and (1, 5), * (-5, 0) and (0, 5). <image> Points (-5, -1), (1, 5), (0, 5), (-5, 0) determine the smallest region with double area of 11. In the second example, it's optimal to make cuts between the following pairs of vertices: * (2, -1) and (0, 2), * (2, -1) and (1, 0), * (-1, 0) and (0, 2). <image> Points (2, -2), (2, -1), (-1, 0) determine one of the smallest regions with double area of 3.
#include <bits/stdc++.h> #pragma GCC optimize(2, 3, "Ofast") #pragma GCC target("avx", "avx2") using namespace std; template <typename T1, typename T2> void ckmin(T1 &a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> void ckmax(T1 &a, T2 b) { if (a < b) a = b; } int read() { int x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f |= ch == '-', ch = getchar(); while (isdigit(ch)) x = 10 * x + ch - '0', ch = getchar(); return f ? -x : x; } template <typename T> void print(T x) { if (x < 0) putchar('-'), x = -x; if (x >= 10) print(x / 10); putchar(x % 10 + '0'); } template <typename T> void print(T x, char let) { print(x), putchar(let); } const int N = 205; template <typename T> int sign(T x) { if (x < 0) return -1; if (x == 0) return 0; return 1; } struct Vec { long long x, y; Vec(long long _x = 0, long long _y = 0) { x = _x, y = _y; } } a[N]; Vec operator+(Vec x, Vec y) { return Vec(x.x + y.x, x.y + y.y); } Vec operator-(Vec x, Vec y) { return Vec(x.x - y.x, x.y - y.y); } long long Cross(Vec x, Vec y) { return x.x * y.y - x.y * y.x; } int n, m; pair<long long, long long> dp[N][N]; bool check(long long area) { for (int len = 3; len <= n; len++) { for (int i = 1, j = len; j <= n; i++, j++) { dp[i][j] = {-1e9, 0}; for (int k = i + 1; k <= j - 1; k++) { pair<long long, long long> f = {dp[i][k].first + dp[k][j].first, dp[i][k].second + dp[k][j].second + Cross(a[k] - a[i], a[j] - a[i])}; if (f.second >= area) f.first++, f.second = 0; ckmax(dp[i][j], f); } } } return dp[1][n].first >= m; } int main() { n = read(), m = read() + 1; for (int i = 1; i <= n; i++) a[i].x = read(), a[i].y = read(); long long l = 0, r = 1e18; while (l < r) { long long mid = l + r + 1 >> 1; if (check(mid)) l = mid; else r = mid - 1; } print(l, '\n'); return 0; }
There are n cities in a row numbered from 1 to n. The cities will be building broadcasting stations. The station in the i-th city has height h_i and range w_i. It can broadcast information to city j if the following constraints are met: * i ≀ j ≀ w_i, and * for each k such that i < k ≀ j, the following condition holds: h_k < h_i. In other words, the station in city i can broadcast information to city j if j β‰₯ i, j is in the range of i-th station, and i is strictly highest on the range from i to j (including city j). At the beginning, for every city i, h_i = 0 and w_i = i. Then q events will take place. During i-th event one of the following will happen: * City c_i will rebuild its station so that its height will be strictly highest among all stations and w_{c_i} will be set to g_i. * Let b_j be the number of stations that can broadcast information to city j. Print the sum of b_j over all j satisfying l_i ≀ j ≀ r_i. Your task is to react to all events and print answers to all queries. Input The first line contains two integers n and q (1 ≀ n, q ≀ 2β‹…10^5) β€” number of cities and number of events. Then q lines follow. The i-th line begins with an integer p_i (p_i = 1 or p_i = 2). If p_i = 1 a station will be rebuilt. Then two integers c_i and g_i (1 ≀ c_i ≀ g_i ≀ n) follow β€” the city in which the station is rebuilt and its new broadcasting range. If p_i = 2 you are given a query. Then two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ n) follow β€” the range of cities in the query. Output For each query, print in a single line the sum of b_j over the given interval. Examples Input 1 3 2 1 1 1 1 1 2 1 1 Output 1 1 Input 5 10 1 3 4 2 3 5 1 1 5 2 1 5 1 4 5 2 2 4 1 2 3 2 1 3 1 5 5 2 2 5 Output 4 10 5 4 5 Note In the first test case, only station 1 reaches city 1 before and after it is rebuilt. In the second test case, after each rebuild, the array b looks as follows: 1. [1, 1, 1, 2, 1]; 2. [1, 2, 2, 3, 2]; 3. [1, 2, 2, 1, 2]; 4. [1, 1, 2, 1, 2]; 5. [1, 1, 2, 1, 1].
#include <bits/stdc++.h> using namespace std; using LL = long long; const int MAXN = 200010; const int INF = 0x7fffffff; class SegTree { public: SegTree() {} void Build(int t, int l, int r) { if (l == r) { x[t] = sum[t] = ox[l]; return; } int mid = (l + r) >> 1; Build(t + t, l, mid); Build(t + t + 1, mid + 1, r); sum[t] = sum[t + t] + sum[t + t + 1]; } void PushDown(int t, int l, int r) { if (l == r) return; if (x[t] == 0) return; x[t + t] += x[t]; x[t + t + 1] += x[t]; LL mid = (l + r) >> 1; sum[t + t] += (mid - l + 1) * x[t]; sum[t + t + 1] += (r - mid) * x[t]; x[t] = 0; } void Insert(int t, int a, int l, int r, int p, int q) { PushDown(t, l, r); if (p <= l && r <= q) { x[t] += a; sum[t] += (r - l + 1LL) * a; return; } int mid = (l + r) >> 1; if (p <= mid) Insert(t + t, a, l, mid, p, q); if (mid + 1 <= q) Insert(t + t + 1, a, mid + 1, r, p, q); sum[t] = sum[t + t] + sum[t + t + 1]; } LL Query(int t, int l, int r, int p, int q) { PushDown(t, l, r); if (p <= l && r <= q) return sum[t]; int mid = (l + r) >> 1; LL ans = 0; if (p <= mid) ans += Query(t + t, l, mid, p, q); if (mid + 1 <= q) ans += Query(t + t + 1, mid + 1, r, p, q); return ans; } int ox[MAXN]; LL x[MAXN * 4], sum[MAXN * 4]; } tree; struct Node { int mx, mx2, mn, mn2, cmx, cmn, tmx, tmn, tad; LL sum; }; class SegmentTreeBeats { public: void Merge(int t) { const int lt = t << 1, rt = t << 1 | 1; x[t].sum = x[lt].sum + x[rt].sum; if (x[lt].mx == x[rt].mx) { x[t].mx = x[lt].mx; x[t].cmx = x[lt].cmx + x[rt].cmx; x[t].mx2 = max(x[lt].mx2, x[rt].mx2); } else if (x[lt].mx > x[rt].mx) { x[t].mx = x[lt].mx; x[t].cmx = x[lt].cmx; x[t].mx2 = max(x[lt].mx2, x[rt].mx); } else { x[t].mx = x[rt].mx; x[t].cmx = x[rt].cmx; x[t].mx2 = max(x[lt].mx, x[rt].mx2); } if (x[lt].mn == x[rt].mn) { x[t].mn = x[lt].mn; x[t].cmn = x[lt].cmn + x[rt].cmn; x[t].mn2 = min(x[lt].mn2, x[rt].mn2); } else if (x[lt].mn < x[rt].mn) { x[t].mn = x[lt].mn; x[t].cmn = x[lt].cmn; x[t].mn2 = min(x[lt].mn2, x[rt].mn); } else { x[t].mn = x[rt].mn; x[t].cmn = x[rt].cmn; x[t].mn2 = min(x[lt].mn, x[rt].mn2); } } void PushAdd(int t, int l, int r, int v) { x[t].sum += (r - l + 1LL) * v; x[t].mx += v; x[t].mn += v; if (x[t].mx2 != -INF) x[t].mx2 += v; if (x[t].mn2 != INF) x[t].mn2 += v; if (x[t].tmx != -INF) x[t].tmx += v; if (x[t].tmn != INF) x[t].tmn += v; x[t].tad += v; } void PushMin(int t, int tg) { if (x[t].mx <= tg) return; x[t].sum += (tg * 1LL - x[t].mx) * x[t].cmx; if (x[t].mn2 == x[t].mx) x[t].mn2 = tg; if (x[t].mn == x[t].mx) x[t].mn = tg; if (x[t].tmx > tg) x[t].tmx = tg; x[t].mx = tg; x[t].tmn = tg; } void PushMax(int t, int tg) { if (x[t].mn > tg) return; x[t].sum += (tg * 1LL - x[t].mn) * x[t].cmn; if (x[t].mx2 == x[t].mn) x[t].mx2 = tg; if (x[t].mx == x[t].mn) x[t].mx = tg; if (x[t].tmn < tg) x[t].tmn = tg; x[t].mn = tg; x[t].tmx = tg; } void PushDown(int t, int l, int r) { const int lt = t << 1, rt = t << 1 | 1; const int mid = (l + r) >> 1; if (x[t].tad) { PushAdd(lt, l, mid, x[t].tad); PushAdd(rt, mid + 1, r, x[t].tad); } if (x[t].tmx != -INF) { PushMax(lt, x[t].tmx); PushMax(rt, x[t].tmx); } if (x[t].tmn != INF) { PushMin(lt, x[t].tmn); PushMin(rt, x[t].tmn); } x[t].tad = 0; x[t].tmx = -INF; x[t].tmn = INF; } void Build(int t, int l, int r) { x[t].tmn = INF; x[t].tmx = -INF; if (l == r) { x[t].sum = x[t].mx = x[t].mn = ox[l]; x[t].mx2 = -INF; x[t].mn2 = INF; x[t].cmx = x[t].cmn = 1; return; } int mid = (l + r) >> 1; Build(t << 1, l, mid); Build(t << 1 | 1, mid + 1, r); Merge(t); } void Add(int t, int l, int r, int L, int R, int v) { if (R < l || r < L) return; if (L <= l && r <= R) return PushAdd(t, l, r, v); int mid = (l + r) >> 1; PushDown(t, l, r); Add(t << 1, l, mid, L, R, v); Add(t << 1 | 1, mid + 1, r, L, R, v); Merge(t); } void SetMin(int t, int l, int r, int L, int R, int v) { if (R < l || r < L || x[t].mx <= v) return; if (L <= l && r <= R && x[t].mx2 < v) { tree.Insert(1, -x[t].cmx, 1, n, v + 1, x[t].mx); return PushMin(t, v); } int mid = (l + r) >> 1; PushDown(t, l, r); SetMin(t << 1, l, mid, L, R, v); SetMin(t << 1 | 1, mid + 1, r, L, R, v); Merge(t); } void SetMax(int t, int l, int r, int L, int R, int v) { if (R < l || r < L || x[t].mn >= v) return; if (L <= l && r <= R && x[t].mn2 > v) return PushMax(t, v); int mid = (l + r) >> 1; PushDown(t, l, r); SetMax(t << 1, l, mid, L, R, v); SetMax(t << 1 | 1, mid + 1, r, L, R, v); Merge(t); } LL QuerySum(int t, int l, int r, int L, int R) { if (R < l || r < L) return 0; if (L <= l && r <= R) return x[t].sum; int mid = (l + r) >> 1; PushDown(t, l, r); return QuerySum(t << 1, l, mid, L, R) + QuerySum(t << 1 | 1, mid + 1, r, L, R); } LL QueryMax(int t, int l, int r, int L, int R) { if (R < l || r < L) return -INF; if (L <= l && r <= R) return x[t].mx; int mid = (l + r) >> 1; PushDown(t, l, r); return max(QueryMax(t << 1, l, mid, L, R), QueryMax(t << 1 | 1, mid + 1, r, L, R)); } LL QueryMin(int t, int l, int r, int L, int R) { if (R < l || r < L) return INF; if (L <= l && r <= R) return x[t].mn; int mid = (l + r) >> 1; PushDown(t, l, r); return min(QueryMin(t << 1, l, mid, L, R), QueryMin(t << 1 | 1, mid + 1, r, L, R)); } int n; int ox[MAXN]; Node x[MAXN * 4]; } treeb; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q; cin >> n >> q; treeb.n = n; for (int i = 1; i <= n; ++i) { tree.ox[i] = 1; treeb.ox[i] = i; } tree.Build(1, 1, n); treeb.Build(1, 1, n); while (q--) { int t, a, b; cin >> t >> a >> b; if (t == 1) { int r = treeb.QueryMax(1, 1, n, a, a); if (r > b) { tree.Insert(1, -1, 1, n, b + 1, r); } else if (r < b) { tree.Insert(1, 1, 1, n, r + 1, b); } if (r != b) { treeb.Add(1, 1, n, a, a, b - r); } if (a == 1) continue; treeb.SetMin(1, 1, n, 1, a - 1, a - 1); } else { cout << tree.Query(1, 1, n, a, b) << "\n"; } } return 0; }
You are given a digital clock with n digits. Each digit shows an integer from 0 to 9, so the whole clock shows an integer from 0 to 10^n-1. The clock will show leading zeroes if the number is smaller than 10^{n-1}. You want the clock to show 0 with as few operations as possible. In an operation, you can do one of the following: * decrease the number on the clock by 1, or * swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show 0. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^3). The first line of each test case contains a single integer n (1 ≀ n ≀ 100) β€” number of digits on the clock. The second line of each test case contains a string of n digits s_1, s_2, …, s_n (0 ≀ s_1, s_2, …, s_n ≀ 9) β€” the number on the clock. Note: If the number is smaller than 10^{n-1} the clock will show leading zeroes. Output For each test case, print one integer: the minimum number of operations needed to make the clock show 0. Example Input 7 3 007 4 1000 5 00000 3 103 4 2020 9 123456789 30 001678294039710047203946100020 Output 7 2 0 5 6 53 115 Note In the first example, it's optimal to just decrease the number 7 times. In the second example, we can first swap the first and last position and then decrease the number by 1. In the third example, the clock already shows 0, so we don't have to perform any operations.
import java.io.*; import java.util.*; public class Problem { public static void main(final String[] args) { final InputStream inputStream = System.in; final OutputStream outputStream = System.out; final FastScanner in = new FastScanner(inputStream); final FastPrintWriter out = new FastPrintWriter(outputStream); final boolean multiTests = true; if (multiTests) { int t = in.nextInt(); while (t-- > 1) { new Solver(in, out).solve(); } } new Solver(in, out).solve(); out.close(); in.close(); } static class Solver { private final FastScanner in; private final FastPrintWriter out; public Solver(FastScanner in, FastPrintWriter out) { this.in = in; this.out = out; } public void solve() { int n = scanInt(); String vector = next(); int[] digits = new int[vector.length()]; for (int i = 0; i < n; i++) { digits[i] = Integer.parseInt(Character.toString(vector.charAt(i))); } int count = digits[n - 1]; digits[n - 1] = 0; for (int i = 0; i < n - 1; i++) { if (digits[i] == 0) { continue; } swap(digits, i, n - 1); count += digits[n - 1] + 1; digits[n - 1] = 0; } out.println(count); } private void swap(int[] array, int i, int j) { int save = array[i]; array[i] = array[j]; array[j] = save; } // InputRead private int scanInt() { return in.nextInt(); } private long scanLong() { return in.nextLong(); } private double scanDouble() { return in.nextDouble(); } private String next() { return in.next(); } private int[] nextIntArray(int len) { int[] array = new int[len]; for (int i = 0; i < len; i++) { array[i] = scanInt(); } return array; } private long[] nextLongArray(int len) { long[] array = new long[len]; for (int i = 0; i < len; i++) { array[i] = scanLong(); } return array; } } static class FastScanner { private final BufferedReader reader; private StringTokenizer st; public FastScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public void close() { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } private void read() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } } public String next() { read(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class FastPrintWriter extends PrintWriter { public FastPrintWriter(OutputStream outputStream) { super(outputStream); } public void print(Object ... objects) { for (int i = 0; i < objects.length - 1; i++) { print(objects[i] + " "); } print(objects[objects.length - 1]); } public void println(Object ... objects) { for (int i = 0; i < objects.length - 1; i++) { print(objects[i] + " "); } println(objects[objects.length - 1]); } public void printArray(int[] array) { for (int i = 0; i < array.length - 1; i++) { print(array[i] + " "); } println(array[array.length - 1]); } } }
You are given a book with n chapters. Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list. Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter. Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 2β‹…10^4). The first line of each test case contains a single integer n (1 ≀ n ≀ 2β‹…10^5) β€” number of chapters. Then n lines follow. The i-th line begins with an integer k_i (0 ≀ k_i ≀ n-1) β€” number of chapters required to understand the i-th chapter. Then k_i integers a_{i,1}, a_{i,2}, ..., a_{i, k_i} (1 ≀ a_{i, j} ≀ n, a_{i, j} β‰  i, a_{i, j} β‰  a_{i, l} for j β‰  l) follow β€” the chapters required to understand the i-th chapter. It is guaranteed that the sum of n and sum of k_i over all testcases do not exceed 2β‹…10^5. Output For each test case, if the entire book can be understood, print how many times you will read it, otherwise print -1. Example Input 5 4 1 2 0 2 1 4 1 2 5 1 5 1 1 1 2 1 3 1 4 5 0 0 2 1 2 1 2 2 2 1 4 2 2 3 0 0 2 3 2 5 1 2 1 3 1 4 1 5 0 Output 2 -1 1 2 5 Note In the first example, we will understand chapters \{2, 4\} in the first reading and chapters \{1, 3\} in the second reading of the book. In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book. In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go. In the fourth example, we will understand chapters \{2, 3, 4\} in the first reading and chapter 1 in the second reading of the book. In the fifth example, we will understand one chapter in every reading from 5 to 1.
#include <bits/stdc++.h> using namespace std; string yes[2] = {"NO\n", "YES\n"}; const long long mod = long long(1e9) + 7; const long long inf = long long(1e16) + 1; bool testc = 1; const int N = 2e5 + 5; int n, i, to[N], x, j, dp[N], o; vector<int> adj[N]; void dfs(int x) { int j, y; for (j = 0; j < adj[x].size(); ++j) { y = adj[x][j]; --to[y]; if (x > y) dp[y] = max(dp[x] + 1, dp[y]); else dp[y] = max(dp[x], dp[y]); if (!to[y]) { to[y] = -1; dfs(y); } } } void solve() { cin >> n; for (i = 1; i <= n; ++i) { adj[i].clear(); dp[i] = 1; to[i] = 0; } for (i = 1; i <= n; ++i) { cin >> to[i]; for (j = 1; j <= to[i]; ++j) { cin >> x; adj[x].push_back(i); } } for (i = 1; i <= n; ++i) if (!to[i]) { to[i] = -1; dfs(i); } for (i = 1; i <= n; ++i) if (to[i] != -1) { cout << "-1\n"; return; } o = 0; for (i = 1; i <= n; ++i) o = max(o, dp[i]); cout << o << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int testcase = 1; if (testc) cin >> testcase; while (testcase-- > 0) { solve(); } return 0; }
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. You are given an integer n. Your goal is to construct and print exactly n different regular bracket sequences of length 2n. Input The first line contains one integer t (1 ≀ t ≀ 50) β€” the number of test cases. Each test case consists of one line containing one integer n (1 ≀ n ≀ 50). Output For each test case, print n lines, each containing a regular bracket sequence of length exactly 2n. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible. Example Input 3 3 1 3 Output ()()() ((())) (()()) () ((())) (())() ()(())
#include <bits/stdc++.h> using namespace std; long long const tax = 1e9 + 7; void setIO() {} long long xx; void helper(vector<string> &v, string s, int n, int m) { if (n == 0 && m == 0) { v.push_back(s); return; } if (v.size() > xx) return; if (n > 0) helper(v, s + "(", n - 1, m + 1); if (m > 0) helper(v, s + ")", n, m - 1); } void generateParenthesis(int n) { vector<string> ans; helper(ans, "", n, 0); for (long long i = 0; i < n; i++) { cout << ans[i] << endl; } } signed main() { setIO(); long long t; cin >> t; while (t--) { long long n; cin >> n; xx = n; generateParenthesis(n); } return 0; }
You are given four integer values a, b, c and m. Check if there exists a string that contains: * a letters 'A'; * b letters 'B'; * c letters 'C'; * no other letters; * exactly m pairs of adjacent equal letters (exactly m such positions i that the i-th letter is equal to the (i+1)-th one). Input The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of testcases. Each of the next t lines contains the description of the testcase β€” four integers a, b, c and m (1 ≀ a, b, c ≀ 10^8; 0 ≀ m ≀ 10^8). Output For each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). Example Input 3 2 2 1 0 1 1 1 1 1 2 3 2 Output YES NO YES Note In the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings. In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice. In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings.
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t>0){ t--; int a = scn.nextInt(); int b = scn.nextInt(); int c = scn.nextInt(); int m = scn.nextInt(); int result = a+b+c-3; if(result<m){ System.out.println("NO"); } else{ int[] arr = new int[3]; arr[0] = a; arr[1]= b; arr[2] = c; int max = 0; int ot = 0; for(int i= 0; i<3; i++){ if(arr[i]>arr[max]){ max = i; } } for(int i= 0; i<3; i++){ if(i!=max){ ot += arr[i]; } } if(arr[max]>ot+m+1){ System.out.println("NO"); } else{ System.out.println("YES"); } } } } }
Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of n heroes, the strength of the i-th hero is equal to a_i. According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to x, then you have to send a hero with a strength of at least x to kill it. If the dragon's attack power is y, then the total strength of the heroes defending the castle should be at least y. The player can increase the strength of any hero by 1 for one gold coin. This operation can be done any number of times. There are m dragons in the game, the i-th of them has defense equal to x_i and attack power equal to y_i. Petya was wondering what is the minimum number of coins he needs to spend to defeat the i-th dragon. Note that the task is solved independently for each dragon (improvements are not saved). Input The first line contains a single integer n (2 ≀ n ≀ 2 β‹… 10^5) β€” number of heroes. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^{12}), where a_i is the strength of the i-th hero. The third line contains a single integer m (1 ≀ m ≀ 2 β‹… 10^5) β€” the number of dragons. The next m lines contain two integers each, x_i and y_i (1 ≀ x_i ≀ 10^{12}; 1 ≀ y_i ≀ 10^{18}) β€” defense and attack power of the i-th dragon. Output Print m lines, i-th of which contains a single integer β€” the minimum number of coins that should be spent to defeat the i-th dragon. Example Input 4 3 6 2 3 5 3 12 7 9 4 14 1 10 8 7 Output 1 2 4 0 2 Note To defeat the first dragon, you can increase the strength of the third hero by 1, then the strength of the heroes will be equal to [3, 6, 3, 3]. To kill the dragon, you can choose the first hero. To defeat the second dragon, you can increase the forces of the second and third heroes by 1, then the strength of the heroes will be equal to [3, 7, 3, 3]. To kill the dragon, you can choose a second hero. To defeat the third dragon, you can increase the strength of all the heroes by 1, then the strength of the heroes will be equal to [4, 7, 3, 4]. To kill the dragon, you can choose a fourth hero. To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon. To defeat the fifth dragon, you can increase the strength of the second hero by 2, then the strength of the heroes will be equal to [3, 8, 2, 3]. To kill the dragon, you can choose a second hero.
import java.io.*; import java.util.*; public class Main { static MyScanner sc = new MyScanner(); static Output out=new Output(); public static void main(String[] args) { // int t=sc.nextInt(); // for(int i=0;i<t;i++) { solve(); // } out.flush(); } public static void solve() { int n=sc.nextInt(); long a[]=sc.nextLongArr(n); Arrays.sort(a); long sum=0; for(int i=0;i<n;i++) sum+=a[i]; int m=sc.nextInt(); int l=a.length; for(int i=0;i<m;i++) { long x=sc.nextLong(),y=sc.nextLong(); int in=Arrays.binarySearch(a, x); if(in>=0) { if(sum-a[in]<y) { out.println(y-(sum-a[in])); } else { out.println(0); } } else { long ans=0; in=-in-1; if(in==l) { ans+=(x-a[l-1]); if(sum-a[l-1]<y) ans+=y-(sum-a[l-1]); out.println(ans); } else if(in==0){ if(sum-a[0]<y) ans+=y-(sum-a[0]); out.println(ans); } else { ans+=x-a[in-1]; if(sum-a[in-1]<y) ans+=y-(sum-a[in-1]); long ans1=0; if(sum-a[in]<y) { ans1+=y-(sum-a[in]); } out.println(Math.min(ans, ans1)); } } } } } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextIntArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArr(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArr(int n) { double a[] = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public String[] nextArr(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public String[] nextLineArr(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = nextLine(); return a; } } class Output{ StringBuilder s=new StringBuilder(); public void println() { s.append("\n"); } public void println(Object x) { s.append(x+"\n"); } public void print(Object x) { s.append(x+""); } public void flush() { System.out.println(s); s=new StringBuilder(); } }
Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has n equipment slots. There is a list of c_i items for the i-th slot, the j-th of them increases the hero strength by a_{i,j}. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, a_{i,1} < a_{i,2} < ... < a_{i,c_i}. For each slot Ivan chooses exactly one item. Let the chosen item for the i-th slot be the b_i-th item in the corresponding list. The sequence of choices [b_1, b_2, ..., b_n] is called a build. The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of m pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned. What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them. Input The first line contains a single integer n (1 ≀ n ≀ 10) β€” the number of equipment slots. The i-th of the next n lines contains the description of the items for the i-th slot. First, one integer c_i (1 ≀ c_i ≀ 2 β‹… 10^5) β€” the number of items for the i-th slot. Then c_i integers a_{i,1}, a_{i,2}, ..., a_{i,c_i} (1 ≀ a_{i,1} < a_{i,2} < ... < a_{i,c_i} ≀ 10^8). The sum of c_i doesn't exceed 2 β‹… 10^5. The next line contains a single integer m (0 ≀ m ≀ 10^5) β€” the number of banned builds. Each of the next m lines contains a description of a banned build β€” a sequence of n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ c_i). The builds are pairwise distinct, and there's at least one build that's not banned. Output Print the build with the maximum strength that is not banned from the game. If there are multiple builds with maximum strength, print any of them. Examples Input 3 3 1 2 3 2 1 5 3 2 4 6 2 3 2 3 3 2 2 Output 2 2 3 Input 3 3 1 2 3 2 1 5 3 2 4 6 2 3 2 3 2 2 3 Output 1 2 3 Input 3 3 1 2 3 2 1 5 3 2 4 6 2 3 2 3 2 2 3 Output 3 2 2 Input 4 1 10 1 4 1 7 1 3 0 Output 1 1 1 1
import java.io.*; import java.util.*; public class D { static int[][] mat; static int compare(int[] x, int[] y) { for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) return x[i] - y[i]; } return 0; } static class node { int sum; int[] arr; public node(int s, int[] a) { sum = s; arr = a; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); mat = new int[n][]; for (int i = 0; i < mat.length; i++) { int size = sc.nextInt(); mat[i] = new int[size]; for (int j = 0; j < mat[i].length; j++) { mat[i][j] = sc.nextInt(); } } int m = sc.nextInt(); TreeSet<int[]> hs = new TreeSet<>((u, v) -> compare(v, u)); for (int i = 0; i < m; i++) { int[] temp = new int[n]; for (int j = 0; j < n; j++) { temp[j] = sc.nextInt(); } hs.add(temp); } TreeSet<int[]> pq = new TreeSet<>((u, v) -> compare(v, u)); int[] temp = new int[n + 1]; for (int i = 0; i < n; i++) { temp[i + 1] = mat[i].length; temp[0] += mat[i][mat[i].length - 1]; } pq.add(temp); int[] ans = new int[n]; while (true) { ans = pq.pollFirst(); // System.out.println("now"); // System.out.println(Arrays.toString(ans)); int[] ser = new int[n]; for (int i = 0; i < ser.length; i++) { ser[i] = ans[i + 1]; } if (!hs.contains(ser)) { break; } for (int i = 0; i < n; i++) { if (ans[i+1] == 1) continue; int[] b = ans.clone(); b[0] -= mat[i][b[i+1] - 1]; b[i+1]--; b[0] += mat[i][b[i+1] - 1]; // System.out.println(Arrays.toString(b)); pq.add(b); } } for (int i = 1; i < ans.length; i++) { pw.print(ans[i]+" "); } // pw.println(" I have the sol but .... no time to write it !! :("); } pw.flush(); } public class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] + sTree[index << 1 | 1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 + q2; } } static ArrayList<Integer> primes; static int[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); if (1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } static char[] bits; static class Trie { static final int R = 2; static class Node { Node[] next = new Node[R]; int count = 0; } Node root = new Node(); void insert(String s) { Node cur = root; cur.count++; for (int i = 0; i < s.length(); i++) { int idx = s.charAt(i) == '0' ? 0 : 1; Node nxt = cur.next[idx]; if (nxt == null) nxt = cur.next[idx] = new Node(); cur = nxt; cur.count++; } } void insert(int n) { Node cur = root; cur.count++; for (int i = 29; i >= 0; i--) { int idx = (n >> i) & 1; Node nxt = cur.next[idx]; if (nxt == null) nxt = cur.next[idx] = new Node(); cur = nxt; cur.count++; } } void remove(String s) { Node cur = root; cur.count--; for (int i = 0; i < s.length(); i++) { int idx = s.charAt(i) == '0' ? 0 : 1; Node nxt = cur.next[idx]; cur = nxt; cur.count--; } } int query(String x) { Node cur = root; String ans = ""; for (int i = 0; i < x.length(); i++) { int idx = x.charAt(i) == '0' ? 1 : 0; Node nxt = cur.next[idx]; if (nxt == null || nxt.count == 0) { ans += 0; nxt = cur.next[idx ^ 1]; } else ans += 1; cur = nxt; } return Integer.parseInt(ans, 2); } int query2(String x) { Node cur = root; String ans = ""; for (int i = 0; i < x.length(); i++) { int idx = x.charAt(i) == '0' ? 1 : 0; Node nxt = cur.next[idx]; if (nxt == null || nxt.count == 0) { ans += 0; nxt = cur.next[idx ^ 1]; } else ans += 1; cur = nxt; } return Integer.parseInt(ans, 2); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
A matrix of size n Γ— m, such that each cell of it contains either 0 or 1, is considered beautiful if the sum in every contiguous submatrix of size 2 Γ— 2 is exactly 2, i. e. every "square" of size 2 Γ— 2 contains exactly two 1's and exactly two 0's. You are given a matrix of size n Γ— m. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the x-th row and the y-th column as (x, y). You have to process the queries of three types: * x y -1 β€” clear the cell (x, y), if there was a number in it; * x y 0 β€” write the number 0 in the cell (x, y), overwriting the number that was there previously (if any); * x y 1 β€” write the number 1 in the cell (x, y), overwriting the number that was there previously (if any). After each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo 998244353. Input The first line contains three integers n, m and k (2 ≀ n, m ≀ 10^6; 1 ≀ k ≀ 3 β‹… 10^5) β€” the number of rows in the matrix, the number of columns, and the number of queries, respectively. Then k lines follow, the i-th of them contains three integers x_i, y_i, t_i (1 ≀ x_i ≀ n; 1 ≀ y_i ≀ m; -1 ≀ t_i ≀ 1) β€” the parameters for the i-th query. Output For each query, print one integer β€” the number of ways to fill the empty cells of the matrix after the respective query, taken modulo 998244353. Example Input 2 2 7 1 1 1 1 2 1 2 1 1 1 1 0 1 2 -1 2 1 -1 1 1 -1 Output 3 1 0 1 2 3 6
#include <bits/stdc++.h> using namespace std; inline int read() { int s = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') s = (s << 3) + (s << 1) + ch - '0', ch = getchar(); return s * f; } const int N = 1e6 + 5, mod = 998244353, inv2 = (mod + 1) >> 1; inline void Add(int &a, int b) { a += (a + b >= mod) ? b - mod : b; } inline int dec(int a, int b) { return (a - b < 0) ? a - b + mod : a - b; } inline int add(int a, int b) { return (a + b >= mod) ? a + b - mod : a + b; } inline int quick_pow(int a, int b) { int ret = 1; for (; b; b >>= 1, a = 1ll * a * a % mod) if (b & 1) ret = 1ll * ret * a % mod; return ret; } int col[3], coltp[N][2], row[3], rowtp[N][2], n, m, k, s[2]; inline int calc() { int ret = add(col[0] ? 0 : quick_pow(2, col[2]), row[0] ? 0 : quick_pow(2, row[2])); if (!s[0]) ret = dec(ret, 1); if (!s[1]) ret = dec(ret, 1); return ret; } inline void work(int x, int y, int val) { if (!coltp[y][0] && !coltp[y][1]) col[2] += val; else if (coltp[y][0] && coltp[y][1]) col[0] += val; else col[1] += val; if (!rowtp[x][0] && !rowtp[x][1]) row[2] += val; else if (rowtp[x][0] && rowtp[x][1]) row[0] += val; else row[1] += val; } inline void ADD(int x, int y, int v) { work(x, y, -1); int a = x & 1, b = y & 1; ++s[a ^ b ^ v]; ++coltp[y][a ^ v]; ++rowtp[x][b ^ v]; work(x, y, 1); } inline void DEC(int x, int y, int v) { work(x, y, -1); int a = x & 1, b = y & 1; --s[a ^ b ^ v]; --coltp[y][a ^ v]; --rowtp[x][b ^ v]; work(x, y, 1); } map<pair<int, int>, int> g; int main() { n = read(); m = read(); k = read(); col[2] = m; row[2] = n; int x, y, opt; while (k--) { x = read(); y = read(); opt = read(); if (g.count(make_pair(x, y))) { int u = g[make_pair(x, y)]; if (u) { DEC(x, y, u - 1); } if (opt == -1) { g[make_pair(x, y)] = 0; } } if (opt == 0) { g[make_pair(x, y)] = 1; ADD(x, y, 0); } else if (opt == 1) { g[make_pair(x, y)] = 2; ADD(x, y, 1); } printf("%d\n", calc()); } return 0; }
A subarray of array a from index l to the index r is the array [a_l, a_{l+1}, ..., a_{r}]. The number of occurrences of the array b in the array a is the number of subarrays of a such that they are equal to b. You are given n arrays A_1, A_2, ..., A_n; the elements of these arrays are integers from 1 to k. You have to build an array a consisting of m integers from 1 to k in such a way that, for every given subarray A_i, the number of occurrences of A_i in the array a is not less than the number of occurrences of each non-empty subarray of A_i in a. Note that if A_i doesn't occur in a, and no subarray of A_i occurs in a, this condition is still met for A_i. Your task is to calculate the number of different arrays a you can build, and print it modulo 998244353. Input The first line contains three integers n, m and k (1 ≀ n, m, k ≀ 3 β‹… 10^5) β€” the number of the given arrays, the desired length of the array a, and the upper bound on the values in the arrays. Then n lines follow. The i-th line represents the array A_i. The first integer in the i-th line is c_i (1 ≀ c_i ≀ m) β€” the number of elements in A_i; then, c_i integers from 1 to k follow β€” the elements of the array A_i. Additional constraint on the input: βˆ‘_{i=1}^n c_i ≀ 3 β‹… 10^5; i. e., the number of elements in the given arrays in total does not exceed 3 β‹… 10^5. Output Print one integer β€” the number of different arrays a you can build, taken modulo 998244353. Examples Input 2 4 3 2 1 2 1 3 Output 5 Input 2 4 3 2 1 2 3 3 2 1 Output 0 Input 1 42 1337 2 13 31 Output 721234447
#include <bits/stdc++.h> using namespace std; template <long long mod> struct modular { long long value; modular(long long x = 0) { value = x % mod; if (value < 0) value += mod; } modular& operator+=(const modular& other) { if ((value += other.value) >= mod) value -= mod; return *this; } modular& operator-=(const modular& other) { if ((value -= other.value) < 0) value += mod; return *this; } modular& operator*=(const modular& other) { value = value * other.value % mod; return *this; } modular& operator/=(const modular& other) { long long a = 0, b = 1, c = other.value, m = mod; while (c != 0) { long long t = m / c; m -= t * c; swap(c, m); a -= t * b; swap(a, b); } a %= mod; if (a < 0) a += mod; value = value * a % mod; return *this; } modular operator+(const modular& rhs) const { return modular(*this) += rhs; } modular operator-(const modular& rhs) const { return modular(*this) -= rhs; } modular operator*(const modular& rhs) const { return modular(*this) *= rhs; } modular operator/(const modular& rhs) const { return modular(*this) /= rhs; } modular& operator++() { return *this += 1; } modular& operator--() { return *this -= 1; } modular operator++(int) { modular res(*this); *this += 1; return res; } modular operator--(int) { modular res(*this); *this -= 1; return res; } modular operator-() const { return modular(-value); } bool operator==(const modular& rhs) const { return value == rhs.value; } bool operator!=(const modular& rhs) const { return value != rhs.value; } bool operator<(const modular& rhs) const { return value < rhs.value; } }; template <long long mod> string to_string(const modular<mod>& x) { return to_string(x.value); } template <long long mod> ostream& operator<<(ostream& stream, const modular<mod>& x) { return stream << x.value; } template <long long mod> istream& operator>>(istream& stream, modular<mod>& x) { stream >> x.value; x.value %= mod; if (x.value < 0) x.value += mod; return stream; } constexpr long long mod = 998244353; using mint = modular<mod>; mint power(mint a, long long n) { mint res = 1; while (n > 0) { if (n & 1) { res *= a; } a *= a; n >>= 1; } return res; } vector<mint> fact(1, 1); vector<mint> finv(1, 1); mint C(int n, int k) { if (n < k || k < 0) { return mint(0); } while ((int)fact.size() < n + 1) { fact.emplace_back(fact.back() * (int)fact.size()); finv.emplace_back(mint(1) / fact.back()); } return fact[n] * finv[k] * finv[n - k]; } struct dsu { vector<int> p; vector<int> sz; int n; dsu(int _n) : n(_n) { p.resize(n); iota(p.begin(), p.end(), 0); sz.assign(n, 1); } inline int get(int x) { if (p[x] == x) { return x; } else { return p[x] = get(p[x]); } } inline bool unite(int x, int y) { x = get(x); y = get(y); if (x == y) { return false; } if (sz[x] > sz[y]) { swap(x, y); } p[x] = y; sz[y] += sz[x]; return true; } inline bool same(int x, int y) { return (get(x) == get(y)); } }; mint root; int base; int max_base; vector<mint> roots; vector<int> rev; void ensure_base(int nbase) { if (roots.empty()) { auto tmp = mod - 1; max_base = 0; while (tmp % 2 == 0) { tmp /= 2; max_base++; } root = 2; while (power(root, (mod - 1) >> 1) == 1) { root += 1; } root = power(root, (mod - 1) >> max_base); base = 1; rev = {0, 1}; roots = {0, 1}; } if (nbase <= base) { return; } rev.resize(1 << nbase); for (int i = 0; i < (1 << nbase); i++) { rev[i] = (rev[i >> 1] >> 1) + ((i & 1) << (nbase - 1)); } roots.resize(1 << nbase); while (base < nbase) { mint z = power(root, 1 << (max_base - 1 - base)); for (int i = 1 << (base - 1); i < (1 << base); i++) { roots[i << 1] = roots[i]; roots[(i << 1) + 1] = roots[i] * z; } base++; } } void ntt(vector<mint>& a) { int n = (int)a.size(); int zeros = __builtin_ctz(n); ensure_base(zeros); int shift = base - zeros; for (int i = 0; i < n; i++) { if (i < (rev[i] >> shift)) { swap(a[i], a[rev[i] >> shift]); } } for (int k = 1; k < n; k <<= 1) { for (int i = 0; i < n; i += 2 * k) { for (int j = 0; j < k; j++) { mint x = a[i + j]; mint y = a[i + j + k] * roots[j + k]; a[i + j] = x + y; a[i + j + k] = x - y; } } } } vector<mint> multiply(vector<mint> a, vector<mint> b) { int need = (int)a.size() + (int)b.size() - 1; int nbase = 0; while ((1 << nbase) < need) { nbase++; } ensure_base(nbase); int sz = 1 << nbase; a.resize(sz); b.resize(sz); ntt(a); ntt(b); mint inv = mint(1) / mint(sz); for (int i = 0; i < sz; i++) { a[i] *= b[i] * inv; } reverse(a.begin() + 1, a.end()); ntt(a); a.resize(need); return a; } vector<mint>& operator*=(vector<mint>& a, const vector<mint>& b) { if (min(a.size(), b.size()) < 150) { vector<mint> c = a; a.assign(a.size() + b.size() - 1, 0); for (int i = 0; i < (int)c.size(); i++) { for (int j = 0; j < (int)b.size(); j++) { a[i + j] += c[i] * b[j]; } } } else { a = multiply(a, b); } return a; } template <typename T> vector<T> operator*(const vector<T>& a, const vector<T>& b) { vector<T> c = a; return c *= b; } template <typename T> vector<T> inverse(const vector<T>& a) { vector<T> h(a); int n = (int)h.size(); T invh0 = T(1) / h[0]; vector<T> u(1, invh0); while ((int)u.size() < n) { int t = (int)u.size(); vector<T> h0; for (int i = 0; i < t; i++) { h0.emplace_back(i < (int)h.size() ? h[i] : 0); } vector<T> c = h0 * u; vector<T> h1; for (int i = t; i < 2 * t; i++) { h1.emplace_back(i < (int)h.size() ? h[i] : 0); } vector<T> aux = u * h1; aux.resize(t); for (int i = 0; i < t; i++) { aux[i] += (i + t < (int)c.size() ? c[i + t] : 0); } vector<T> v = aux * u; v.resize(t); for (int i = 0; i < t; i++) { u.emplace_back(-v[i]); } } u.resize(n); return u; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m, k; cin >> n >> m >> k; vector<vector<int>> a; for (int i = 0; i < n; i++) { int c; cin >> c; vector<int> b(c); for (int j = 0; j < c; j++) { cin >> b[j]; b[j]--; } a.emplace_back(b); } sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); n = (int)a.size(); vector<int> nxt(k, -1), pre(k, 0); dsu uf(k + 1); for (int i = 0; i < n; i++) { for (int j = 0; j < (int)a[i].size() - 1; j++) { uf.unite(a[i][j], a[i][j + 1]); if (nxt[a[i][j]] != a[i][j + 1]) { if (nxt[a[i][j]] == -1) { nxt[a[i][j]] = a[i][j + 1]; pre[a[i][j + 1]]++; } else { uf.unite(a[i][j], k); } } } } vector<mint> b(m + 1); for (int i = 0; i < k; i++) { if (uf.same(i, k) || pre[i]) { continue; } vector<int> c; c.emplace_back(i); int now = i; while (nxt[now] != -1) { c.emplace_back(nxt[now]); now = nxt[now]; if (pre[now] != 1) { c.clear(); break; } } if ((int)c.size() == uf.sz[uf.get(i)] && (int)c.size() <= m) { b[c.size()]++; } else { uf.unite(i, k); } }; vector<mint> c(m + 1); c[0] = 1; for (int i = 1; i <= m; i++) { c[i] = -b[i]; } c = inverse(c); b *= c; cout << b[m] << '\n'; return 0; }