input
stringlengths
29
13k
output
stringlengths
9
73.4k
This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even. There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of cows on the plane, one at every point with integer coordinates. Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting 3 distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting. Find the number of interesting fences. Input The first line contains the integer n (3 ≀ n ≀ 6000), the number of fence posts which Gregor can choose to form the vertices of a fence. Each of the next n line contains two integers x and y (0 ≀ x,y ≀ 10^7, x and y are even), where (x,y) is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line. Output Print a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts. Examples Input 3 0 0 2 0 0 4 Output 1 Input 5 0 0 2 16 30 14 4 6 2 10 Output 3 Note In the first example, there is only 1 fence. That fence is interesting since its area is 4 and there is 1 enclosed cow, marked in red. <image> In the second example, there are 3 interesting fences. * (0,0) β€” (30,14) β€” (2,10) * (2,16) β€” (30,14) β€” (2,10) * (30,14) β€” (4,6) β€” (2,10)
#include <bits/stdc++.h> using namespace std; int cnt[2][2]; int main() { int n, i, j, k; scanf("%d", &n); for (i = 1; i <= n; i++) { int x, y; scanf("%d%d", &x, &y); x >>= 1; y >>= 1; cnt[x & 1][y & 1]++; } long long ans = 0; for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) { k = cnt[i][j]; ans += 1ll * k * (k - 1) / 2 * (k - 2) / 3 + 1ll * k * (k - 1) / 2 * (n - k); } printf("%lld\n", ans); }
This is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be both odd and even. There are n fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of cows on the plane, one at every point with integer coordinates. Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting 3 distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting. Find the number of interesting fences. Input The first line contains the integer n (3 ≀ n ≀ 6000), the number of fence posts which Gregor can choose to form the vertices of a fence. Each of the next n line contains two integers x and y (0 ≀ x,y ≀ 10^7, where (x,y) is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line. Output Print a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts. Examples Input 3 0 0 2 0 0 4 Output 1 Input 4 1 8 0 6 5 2 5 6 Output 1 Input 10 170 59 129 54 5 98 129 37 58 193 154 58 24 3 13 138 136 144 174 150 Output 29 Note In the first example, there is only 1 fence. That fence is interesting since its area is 4 and there is 1 enclosed cow, marked in red. <image> In the second example, there are 4 possible fences. Only one of them is interesting however. That fence has an area of 8 and 5 enclosed cows. <image>
#include <bits/stdc++.h> using namespace std; inline int read() { int s = 0, w = 1, ch = getchar(); while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); } while (isdigit(ch)) { s = (s << 3) + (s << 1) + ch - 48; ch = getchar(); } return s * w; } const int maxn = 6050; int n, x[maxn], y[maxn]; int cn[maxn][4][4][4]; long long sum2, sum6; inline int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } inline int calc(int i1, int j1, int i2, int j2, int i3, int j3) { return i1 * (j2 - j3) + i2 * (j3 - j1) + i3 * (j1 - j2); } signed main() { n = read(); for (int i = 1; i <= n; i++) x[i] = read(), y[i] = read(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (j == i) continue; cn[i][x[j] % 4][y[j] % 4][gcd(abs(x[j] - x[i]), abs(y[j] - y[i])) % 4]++; } } for (int p = 1; p <= n; p++) { for (int i1 = 0; i1 < 4; i1++) for (int j1 = 0; j1 < 4; j1++) for (int z1 = 0; z1 < 4; z1++) { if (cn[p][i1][j1][z1] == 0) continue; int rec = cn[p][i1][j1][z1]; cn[p][i1][j1][z1]--; for (int i2 = i1 & 1; i2 < 4; i2 += 2) for (int j2 = j1 & 1; j2 < 4; j2 += 2) for (int z2 = z1 & 1; z2 < 4; z2 += 2) { int S = calc(x[p] % 4, y[p] % 4, i1, j1, i2, j2) / 2, z3 = gcd(abs(i1 - i2), abs(j1 - j2)); if ((S - (z1 + z2 + z3) / 2 + 1) & 1) { if (z1 % 2 == 0) sum6 += rec * cn[p][i2][j2][z2]; else sum2 += rec * cn[p][i2][j2][z2]; } } cn[p][i1][j1][z1]++; } } long long ans = sum6 / 6 + sum2 / 2; cout << ans << endl; return 0; }
Two painters, Amin and Benj, are repainting Gregor's living room ceiling! The ceiling can be modeled as an n Γ— m grid. For each i between 1 and n, inclusive, painter Amin applies a_i layers of paint to the entire i-th row. For each j between 1 and m, inclusive, painter Benj applies b_j layers of paint to the entire j-th column. Therefore, the cell (i,j) ends up with a_i+b_j layers of paint. Gregor considers the cell (i,j) to be badly painted if a_i+b_j ≀ x. Define a badly painted region to be a maximal connected component of badly painted cells, i. e. a connected component of badly painted cells such that all adjacent to the component cells are not badly painted. Two cells are considered adjacent if they share a side. Gregor is appalled by the state of the finished ceiling, and wants to know the number of badly painted regions. Input The first line contains three integers n, m and x (1 ≀ n,m ≀ 2β‹… 10^5, 1 ≀ x ≀ 2β‹… 10^5) β€” the dimensions of Gregor's ceiling, and the maximum number of paint layers in a badly painted cell. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2β‹… 10^5), the number of paint layers Amin applies to each row. The third line contains m integers b_1, b_2, …, b_m (1 ≀ b_j ≀ 2β‹… 10^5), the number of paint layers Benj applies to each column. Output Print a single integer, the number of badly painted regions. Examples Input 3 4 11 9 8 5 10 6 7 2 Output 2 Input 3 4 12 9 8 5 10 6 7 2 Output 1 Input 3 3 2 1 2 1 1 2 1 Output 4 Input 5 23 6 1 4 3 5 2 2 3 1 6 1 5 5 6 1 3 2 6 2 3 1 6 1 4 1 6 1 5 5 Output 6 Note The diagram below represents the first example. The numbers to the left of each row represent the list a, and the numbers above each column represent the list b. The numbers inside each cell represent the number of paint layers in that cell. The colored cells correspond to badly painted cells. The red and blue cells respectively form 2 badly painted regions. <image>
#include <bits/stdc++.h> using namespace std; template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string& s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string)s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto& x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } template <typename T, class F = function<T(const T&, const T&)>> class SparseTable { public: int n; vector<vector<T>> mat; F func; SparseTable(const vector<T>& a, const F& f) : func(f) { n = static_cast<int>(a.size()); int max_log = 32 - __builtin_clz(n); mat.resize(max_log); mat[0] = a; for (int j = 1; j < max_log; j++) { mat[j].resize(n - (1 << j) + 1); for (int i = 0; i <= n - (1 << j); i++) { mat[j][i] = func(mat[j - 1][i], mat[j - 1][i + (1 << (j - 1))]); } } } T get(int from, int to) const { assert(0 <= from && from <= to && to <= n - 1); int lg = 32 - __builtin_clz(to - from + 1) - 1; return func(mat[lg][from], mat[lg][to - (1 << lg) + 1]); } }; template <typename T> class fenwick { public: vector<T> fenw; int n; fenwick(int _n) : n(_n) { fenw.resize(n); } void modify(int x, T v) { while (x < n) { fenw[x] += v; x |= (x + 1); } } T get(int x) { T v{}; while (x >= 0) { v += fenw[x]; x = (x & (x + 1)) - 1; } return v; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m, x; cin >> n >> m >> x; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; a[i] = min(a[i], x); } vector<int> b(m); for (int i = 0; i < m; i++) { cin >> b[i]; b[i] = min(b[i], x); } long long V = 0; long long E = 0; long long F = 0; { auto sa = a; sort(sa.begin(), sa.end()); auto sb = b; sort(sb.begin(), sb.end()); int j = m; for (int i = 0; i < n; i++) { while (j > 0 && sb[j - 1] + sa[i] > x) { --j; } V += j; } } {{vector<int> sa(n - 1); for (int i = 0; i < n - 1; i++) { sa[i] = max(a[i], a[i + 1]); } sort(sa.begin(), sa.end()); auto sb = b; sort(sb.begin(), sb.end()); int j = m; for (int i = 0; i < n - 1; i++) { while (j > 0 && sb[j - 1] + sa[i] > x) { --j; } E += j; } } { auto sa = a; sort(sa.begin(), sa.end()); vector<int> sb(m - 1); for (int i = 0; i < m - 1; i++) { sb[i] = max(b[i], b[i + 1]); } sort(sb.begin(), sb.end()); int j = m - 1; for (int i = 0; i < n; i++) { while (j > 0 && sb[j - 1] + sa[i] > x) { --j; } E += j; } } } { auto Make = [&](const vector<int>& v) { int sz = (int)v.size(); vector<int> pr(sz), ne(sz); for (int i = 0; i < sz; i++) { pr[i] = i - 1; ne[i] = i + 1; } vector<int> order(sz); iota(order.begin(), order.end(), 0); sort(order.begin(), order.end(), [&](int i, int j) { return v[i] > v[j]; }); SparseTable<int> st(v, [&](int i, int j) { return max(i, j); }); vector<tuple<int, int, int>> ret; for (int i = 0; i < sz - 1; i++) { ret.emplace_back(max(v[i], v[i + 1]), x, max(v[i], v[i + 1])); } for (int i : order) { if (pr[i] >= 0 && ne[i] < sz) { int v0 = max(v[pr[i]], v[ne[i]]); int v1 = v[i]; int v2 = st.get(pr[i], ne[i]); if (v0 < v1) { ret.emplace_back(v0, v1, v2); } } if (pr[i] != -1) { ne[pr[i]] = ne[i]; } if (ne[i] != sz) { pr[ne[i]] = pr[i]; } } return ret; }; vector<tuple<int, int, int>> r = Make(a); vector<tuple<int, int, int>> c = Make(b); 42; 42; vector<vector<pair<int, int>>> qs(x + 1); for (auto& q : c) { qs[x - get<2>(q)].emplace_back(x - get<1>(q) + 1, x - get<0>(q)); } vector<vector<int>> ev(x + 1); for (auto& p : r) { ev[get<0>(p)].push_back(get<2>(p)); ev[get<1>(p)].push_back(~get<2>(p)); } fenwick<int> fenw(x + 1); for (int i = 1; i <= x; i++) { for (int e : ev[i]) { if (e >= 1) { fenw.modify(e, +1); } else { fenw.modify(~e, -1); } } for (auto& q : qs[i]) { F += fenw.get(q.second) - fenw.get(q.first - 1); } } } cout << V - E + F << '\n'; return 0; }
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them. Gregor's favorite prime number is P. Gregor wants to find two bases of P. Formally, Gregor is looking for two integers a and b which satisfy both of the following properties. * P mod a = P mod b, where x mod y denotes the remainder when x is divided by y, and * 2 ≀ a < b ≀ P. Help Gregor find two bases of his favorite prime number! Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 1000). Each subsequent line contains the integer P (5 ≀ P ≀ {10}^9), with P guaranteed to be prime. Output Your output should consist of t lines. Each line should consist of two integers a and b (2 ≀ a < b ≀ P). If there are multiple possible solutions, print any. Example Input 2 17 5 Output 3 5 2 4 Note The first query is P=17. a=3 and b=5 are valid bases in this case, because 17 mod 3 = 17 mod 5 = 2. There are other pairs which work as well. In the second query, with P=5, the only solution is a=2 and b=4.
#include <bits/stdc++.h> int main() { int t; scanf("%d", &t); long long int array[t]; for (int i = 0; i < t; i++) { scanf("%lld", &array[i]); } for (int i = 0; i < t; i++) { printf("%d %lld\n", 2, array[i] - 1); } }
There is a chessboard of size n by n. The square in the i-th row from top and j-th column from the left is labelled (i,j). Currently, Gregor has some pawns in the n-th row. There are also enemy pawns in the 1-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from (i,j) to (i-1,j)) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from (i,j) to either (i-1,j-1) or (i-1,j+1)) if and only if there is an enemy pawn in that square. The enemy pawn is also removed. Gregor wants to know what is the maximum number of his pawns that can reach row 1? Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row 1, it is stuck and cannot make any further moves. Input The first line of the input contains one integer t (1≀ t≀ 2β‹… 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of three lines. The first line contains a single integer n (2≀ n≀ 2β‹…{10}^{5}) β€” the size of the chessboard. The second line consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to an enemy pawn in the i-th cell from the left, and 0 corresponds to an empty cell. The third line consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to a Gregor's pawn in the i-th cell from the left, and 0 corresponds to an empty cell. It is guaranteed that the sum of n across all test cases is less than 2β‹…{10}^{5}. Output For each test case, print one integer: the maximum number of Gregor's pawns which can reach the 1-st row. Example Input 4 3 000 111 4 1111 1111 3 010 010 5 11001 00000 Output 3 4 0 0 Note In the first example, Gregor can simply advance all 3 of his pawns forward. Thus, the answer is 3. In the second example, Gregor can guarantee that all 4 of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"! <image> In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end. In the fourth example, Gregor has no pawns, so the answer is clearly 0.
for _ in range(int(input())): n = int(input()) s = list(map(int,list(input()))) m = list(map(int,list(input()))) ans = 0 if m[0] == 1: if s[0]==0: ans +=1 elif s[1] == 1: ans +=1; s[1] = 2 for x in range(1, n): if m[x] == 1: if s[x] == 0: ans +=1 elif s[x-1] == 1: ans += 1 elif x+1 != n and s[x+1] == 1: ans +=1 s[x + 1] = 2 print(ans)
When you play the game of thrones, you win, or you die. There is no middle ground. Cersei Lannister, A Game of Thrones by George R. R. Martin There are n nobles, numbered from 1 to n. Noble i has a power of i. There are also m "friendships". A friendship between nobles a and b is always mutual. A noble is defined to be vulnerable if both of the following conditions are satisfied: * the noble has at least one friend, and * all of that noble's friends have a higher power. You will have to process the following three types of queries. 1. Add a friendship between nobles u and v. 2. Remove a friendship between nobles u and v. 3. Calculate the answer to the following process. The process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles. Note that the results of the process are not carried over between queries, that is, every process starts with all nobles being alive! Input The first line contains the integers n and m (1 ≀ n ≀ 2β‹… 10^5, 0 ≀ m ≀ 2β‹… 10^5) β€” the number of nobles and number of original friendships respectively. The next m lines each contain the integers u and v (1 ≀ u,v ≀ n, u β‰  v), describing a friendship. No friendship is listed twice. The next line contains the integer q (1 ≀ q ≀ 2β‹… {10}^{5}) β€” the number of queries. The next q lines contain the queries themselves, each query has one of the following three formats. * 1 u v (1 ≀ u,v ≀ n, u β‰  v) β€” add a friendship between u and v. It is guaranteed that u and v are not friends at this moment. * 2 u v (1 ≀ u,v ≀ n, u β‰  v) β€” remove a friendship between u and v. It is guaranteed that u and v are friends at this moment. * 3 β€” print the answer to the process described in the statement. Output For each type 3 query print one integer to a new line. It is guaranteed that there will be at least one type 3 query. Examples Input 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 Output 2 1 Input 4 3 2 3 3 4 4 1 1 3 Output 1 Note Consider the first example. In the first type 3 query, we have the diagram below. In the first round of the process, noble 1 is weaker than all of his friends (2 and 3), and is thus killed. No other noble is vulnerable in round 1. In round 2, noble 3 is weaker than his only friend, noble 4, and is therefore killed. At this point, the process ends, and the answer is 2. <image> In the second type 3 query, the only surviving noble is 4. The second example consists of only one type 3 query. In the first round, two nobles are killed, and in the second round, one noble is killed. The final answer is 1, since only one noble survives. <image>
import java.io.*; import java.util.*; public class C { static TreeSet<Integer> g[]; public static void main(String[] args) { FastReader f = new FastReader(); StringBuffer sb=new StringBuffer(); // int test=f.nextInt(); // out: // while(test-->0) // { //leaves which are bigger than thier parents will survive int n=f.nextInt(); int m=f.nextInt(); g=new TreeSet[n+1]; for(int i=0;i<=n;i++) g[i]=new TreeSet<>(); for(int i=0;i<m;i++) { int x=f.nextInt(); int y=f.nextInt(); g[x].add(y); g[y].add(x); } Set<Integer> set=new HashSet<>(); for(int i=1;i<=n;i++) { if(g[i].size()==0) set.add(i); else if(g[i].last()<i) set.add(i); } int q=f.nextInt(); while(q-->0) { int type=f.nextInt(); if(type==1) { int x=f.nextInt(); int y=f.nextInt(); if(set.contains(x)) set.remove(x); if(set.contains(y)); set.remove(y); g[x].add(y); g[y].add(x); if(g[x].size()==0 || g[x].last()<x) set.add(x); if(g[y].size()==0 || g[y].last()<y) set.add(y); } if(type==2) { int x=f.nextInt(); int y=f.nextInt(); if(set.contains(x)) set.remove(x); if(set.contains(y)); set.remove(y); g[x].remove(y); g[y].remove(x); if(g[x].size()==0 || g[x].last()<x) set.add(x); if(g[y].size()==0 || g[y].last()<y) set.add(y); } if(type==3) sb.append(set.size()+"\n"); } // } System.out.println(sb); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { 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; } } }
British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends." It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}, …, a_j to be a friend group if and only if there exists an integer m β‰₯ 2 such that a_i mod m = a_{i+1} mod m = … = a_j mod m, where x mod y denotes the remainder when x is divided by y. Your friend Gregor wants to know the size of the largest friend group in a. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 2β‹… 10^4). Each test case begins with a line containing the integer n (1 ≀ n ≀ 2 β‹… 10^5), the size of the array a. The next line contains n positive integers a_1, a_2, …, a_n (1 ≀ a_i ≀ {10}^{18}), representing the contents of the array a. It is guaranteed that all the numbers in a are distinct. It is guaranteed that the sum of n over all test cases is less than 2β‹… 10^5. Output Your output should consist of t lines. Each line should consist of a single integer, the size of the largest friend group in a. Example Input 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 Output 3 3 2 6 Note In the first test case, the array is [1,5,2,4,6]. The largest friend group is [2,4,6], since all those numbers are congruent to 0 modulo 2, so m=2. In the second test case, the array is [8,2,5,10]. The largest friend group is [8,2,5], since all those numbers are congruent to 2 modulo 3, so m=3. In the third case, the largest friend group is [1000,2000]. There are clearly many possible values of m that work.
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,mod1=998244353l,inf=(long)1e18+5; // 1111111999999, 311111111111113 static void solve1() throws IOException{ int n=int_v(read()); long[] a=long_arr(); if(n<=1){out.write(1+"\n");return;} List<Long> l=new ArrayList<>(); for(int i=0;i+1<n;i++){ l.add(Math.abs(a[i]-a[i+1])); } int k=l.size(); int[] pow=new int[20+1],log=new int[n+1]; pow[0]=1;log[1]=0; for(int i=2;i<=n;i++)log[i]=log[i/2]+1; for(int i=1;i<=20;i++)pow[i]=pow[i-1]*2; long[][] dp=new long[k+1][20]; for(int i=0;i<l.size();i++)dp[i][0]=(long)l.get(i); for(int i=1;i<20;i++){ for(int j=0;j<k;j++){ dp[j][i]=gcd(dp[Math.min(j+pow[i-1],k-1)][i-1],dp[j][i-1]); } //out.write(dp[0][i-1]+", "); } for(int i=0;i<20;i++){ dp[k][i]=dp[k-1][i]; } int l1=1,r=k,ans=0; while(l1<=r){ int m=(l1+r)/2; boolean ok=false; for(int i=0;i<k&&k-i>=m;i++){ int len=log[m]; long tmp=gcd(dp[i][len],dp[i+m-pow[len]][len]); if(tmp>=2){ok=true;break;} } if(ok){ ans=m;l1=m+1; } else r=m-1; } out.write((ans+1)+"\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve1(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Polycarp must pay exactly n burles at the checkout. He has coins of two nominal values: 1 burle and 2 burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other. Thus, Polycarp wants to minimize the difference between the count of coins of 1 burle and 2 burles being used. Help him by determining two non-negative integer values c_1 and c_2 which are the number of coins of 1 burle and 2 burles, respectively, so that the total value of that number of coins is exactly n (i. e. c_1 + 2 β‹… c_2 = n), and the absolute value of the difference between c_1 and c_2 is as little as possible (i. e. you must minimize |c_1-c_2|). Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of one line. This line contains one integer n (1 ≀ n ≀ 10^9) β€” the number of burles to be paid by Polycarp. Output For each test case, output a separate line containing two integers c_1 and c_2 (c_1, c_2 β‰₯ 0) separated by a space where c_1 is the number of coins of 1 burle and c_2 is the number of coins of 2 burles. If there are multiple optimal solutions, print any one. Example Input 6 1000 30 1 32 1000000000 5 Output 334 333 10 10 1 0 10 11 333333334 333333333 1 2 Note The answer for the first test case is "334 333". The sum of the nominal values of all coins is 334 β‹… 1 + 333 β‹… 2 = 1000, whereas |334 - 333| = 1. One can't get the better value because if |c_1 - c_2| = 0, then c_1 = c_2 and c_1 β‹… 1 + c_1 β‹… 2 = 1000, but then the value of c_1 isn't an integer. The answer for the second test case is "10 10". The sum of the nominal values is 10 β‹… 1 + 10 β‹… 2 = 30 and |10 - 10| = 0, whereas there's no number having an absolute value less than 0.
t = int(input()) for _ in range(t): n = int(input()) c1,c2 = 0,0 if n%3==0: c1 = n//3 c2 = n//3 elif n%3==1: c1 = (n+2)//3 c2 = c1-1 else: c2 = (n+1)//3 c1 = c2-1 print(c1,c2)
This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1. Paul and Mary have a favorite string s which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met: 1. each letter of the string is either painted in exactly one color (red or green) or isn't painted; 2. each two letters which are painted in the same color are different; 3. the number of letters painted in red is equal to the number of letters painted in green; 4. the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string s equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure. <image> The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find k β€” the number of red (or green, these numbers are equal) letters in a wonderful coloring. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then t test cases follow. Each test case consists of one non-empty string s which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed 50. Output For each test case, output a separate line containing one non-negative integer k β€” the number of letters which will be painted in red in a wonderful coloring. Example Input 5 kzaaa codeforces archive y xxxxxx Output 2 5 3 0 1 Note The first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing 3 or more red letters because the total number of painted symbols will exceed the string's length. The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than 5 doesn't exist. The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible. The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green. The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class A extends Thread { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { 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; } int[] nextArrayInt(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } String[] nextArrayString(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLine(); } return arr; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new Thread(null, new A(), "Main", 1 << 28).start(); } public void run() { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } private static int factorial(int n) { if (n == 0 || n == 1) return 1; return n * factorial(n-1); } private static int nCr(int n, int r){ return factorial(n)/(factorial(r)*factorial(n-r)); } private static void solve() { String s = scanner.nextLine(); int n = s.length(); int[] count = new int[26]; for(int i = 0; i < n; i++){ char c = s.charAt(i); count[c-'a']++; } int two = 0; int one = 0; for(int i = 0; i < count.length; i++){ if (count[i] == 1) { one++; } else if (count[i] >= 2){ two++; } } int ans = two + (one/2); out.println(ans); } }
This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely. Recently, Paul and Mary have found a new favorite sequence of integers a_1, a_2, ..., a_n. They want to paint it using pieces of chalk of k colors. The coloring of a sequence is called wonderful if the following conditions are met: 1. each element of the sequence is either painted in one of k colors or isn't painted; 2. each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color); 3. let's calculate for each of k colors the number of elements painted in the color β€” all calculated numbers must be equal; 4. the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2] and k=3. One of the wonderful colorings of the sequence is shown in the figure. <image> The example of a wonderful coloring of the sequence a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2] and k=3. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence a. Input The first line contains one integer t (1 ≀ t ≀ 10000) β€” the number of test cases. Then t test cases follow. Each test case consists of two lines. The first one contains two integers n and k (1 ≀ n ≀ 2β‹…10^5, 1 ≀ k ≀ n) β€” the length of a given sequence and the number of colors, respectively. The second one contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ n). It is guaranteed that the sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output Output t lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of n integers c_1, c_2, ..., c_n (0 ≀ c_i ≀ k) separated by spaces where * c_i=0, if i-th element isn't painted; * c_i>0, if i-th element is painted in the c_i-th color. Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one. Example Input 6 10 3 3 1 1 1 1 10 3 10 10 2 4 4 1 1 1 1 1 1 1 13 1 3 1 4 1 5 9 2 6 5 3 5 8 9 13 2 3 1 4 1 5 9 2 6 5 3 5 8 9 13 3 3 1 4 1 5 9 2 6 5 3 5 8 9 Output 1 1 0 2 3 2 2 1 3 3 4 2 1 3 1 0 0 1 1 0 1 1 1 0 1 1 1 0 2 1 2 2 1 1 1 1 2 1 0 2 2 1 1 3 2 1 3 3 1 2 2 3 2 0 Note In the first test case, the answer is shown in the figure in the statement. The red color has number 1, the blue color β€” 2, the green β€” 3.
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; vector<int> a(n); vector<int> res(n); for (int &x : a) cin >> x; vector<vector<int>> pos(n + 1); for (int i = 0; i < n; i++) { pos[a[i]].push_back(i); } vector<vector<int>> b; for (int i = 1; i <= n; i++) { if (pos[i].size() > 0) { vector<int> x = {int(pos[i].size()), i}; b.push_back(x); } } sort(b.begin(), b.end(), greater<vector<int>>()); int times = 0; int total = 0; for (vector<int> x : b) { if (x[0] >= k) times += 1; else total += x[0]; } times += total / k; int j = 1; for (vector<int> x : b) { int num = x[1]; int occurrence = x[0]; if (occurrence >= k) { times--; for (int i = 0; i < k; i++) { res[pos[num][i]] = i + 1; } } else { if (times > 0) { for (int i : pos[num]) { if (times > 0) res[i] = j; if (j == k) { times--; j = 1; } else { j++; } } } } } for (int i = 0; i < n; i++) { cout << res[i] << " "; } cout << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t = 1; cin >> t; while (t--) solve(); return 0; }
Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'! To compose a story, Stephen wrote out n words consisting of the first 5 lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story. Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together. For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs 5 times, all other letters occur 4 times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total). You are given a sequence of n words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output 0. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of the words in the sequence. Then n lines follow, each of them contains a word β€” a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of n over all test cases doesn't exceed 2 β‹… 10^5; the sum of the lengths of all words over all test cases doesn't exceed 4 β‹… 10^5. Output For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story. Example Input 6 3 bac aaada e 3 aba abcde aba 2 baba baba 4 ab ab c bc 5 cbdca d a d e 3 b c ca Output 3 2 0 2 3 2 Note In the first test case of the example, all 3 words can be used to make an interesting story. The interesting story is "bac aaada e". In the second test case of the example, the 1-st and the 3-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time. In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is 0. In the fourth test case of the example, Stephen can use the 3-rd and the 4-th words to make an interesting story. The interesting story is "c bc".
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CInterestingStory solver = new CInterestingStory(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CInterestingStory { int[][] cnt; int[] len; int n; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); cnt = new int[n][5]; len = new int[n]; for (int i = 0; i < n; i++) { String s = in.nextString(); len[i] = s.length(); for (int j = 0; j < s.length(); j++) { cnt[i][s.charAt(j) - 'a']++; } } int res = 0; for (int i = 0; i < 5; i++) { res = Math.max(res, helper(i)); } out.println(res); } private int helper(int i) { int[] tmp = new int[n]; for (int j = 0; j < n; j++) { tmp[j] = 2 * cnt[j][i] - len[j]; } Arrays.sort(tmp); int sum = 0; int cnt = 0; for (int j = n - 1; j >= 0; j--) { sum += tmp[j]; cnt++; if (sum <= 0) { return cnt - 1; } } return n; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
The only difference between this problem and D2 is that you don't have to provide the way to construct the answer in this problem, but you have to do it in D2. There's a table of n Γ— m cells (n rows and m columns). The value of n β‹… m is even. A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other). You need to find out whether it is possible to place nm/2 dominoes on the table so that exactly k of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. Each test case consists of a single line. The line contains three integers n, m, k (1 ≀ n,m ≀ 100, 0 ≀ k ≀ nm/2, n β‹… m is even) β€” the number of rows, columns and horizontal dominoes, respectively. Output For each test case output "YES", if it is possible to place dominoes in the desired way, or "NO" otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer). Example Input 8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1 Output YES YES YES NO YES NO YES NO
import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(t): m,n,k = map(int,input().split()) # if m==1: # if k==m*n//2: print("YES") # else: print("NO") # return # if n==1: # if k==0: print("YES") # else: print("NO") # return if m%2==1: if (m*n//2-k)%2==0 and k>=n//2: print("YES") else: print("NO") elif n%2==1: if k%2==0 and (m*n//2-k)>=m//2: print("YES") else: print("NO") else: if k%2==0: print("YES") else: print("NO") T = int(input()) t = 1 while t<=T: main(t) t += 1
The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem. There's a table of n Γ— m cells (n rows and m columns). The value of n β‹… m is even. A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other). You need to place nm/2 dominoes on the table so that exactly k of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. Each test case consists of a single line. The line contains three integers n, m, k (1 ≀ n,m ≀ 100, 0 ≀ k ≀ nm/2, n β‹… m is even) β€” the count of rows, columns and horizontal dominoes, respectively. Output For each test case: * print "NO" if it's not possible to place the dominoes on the table in the described way; * otherwise, print "YES" on a separate line, then print n lines so that each of them contains m lowercase letters of the Latin alphabet β€” the layout of the dominoes on the table. Each cell of the table must be marked by the letter so that for every two cells having a common side, they are marked by the same letters if and only if they are occupied by the same domino. I.e. both cells of the same domino must be marked with the same letter, but two dominoes that share a side must be marked with different letters. If there are multiple solutions, print any of them. Example Input 8 4 4 2 2 3 0 3 2 3 1 2 0 2 4 2 5 2 2 2 17 16 2 1 1 Output YES accx aegx bega bdda YES aha aha YES zz aa zz NO YES aaza bbza NO YES bbaabbaabbaabbaay ddccddccddccddccy NO
# Author: $%U%$ # Time: $%Y%$-$%M%$-$%D%$ $%h%$:$%m%$:$%s%$ import io import os import collections import math import functools import itertools import bisect import heapq from sys import stdin, stdout, stderr from collections import * from math import * from functools import * from itertools import * from heapq import * from bisect import bisect_left, bisect_right, insort_left, insort_right input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_ints(): return list(map(int, input().split())) def get_int(): return int(input()) def get_str(): return "".join(list(map(chr, input()))[:-1]) def eprint(*args): stderr.write(", ".join(map(str, args)) + "\n") def print(*args): stdout.write(" ".join(map(str, args)) + "\n") # **************************************************************************** # t = get_int() for tt in range(t): n, m, hor = get_ints() total = (n * m) // 2 vert = total - hor h_forced = v_forced = 0 both = (((n // 2) * 2) * ((m // 2) * 2)) // 2 if n % 2 == 1: h_forced = m // 2 elif m % 2 == 1: v_forced = n // 2 if h_forced > hor or v_forced > vert: print("NO") continue hor -= h_forced vert -= v_forced if hor % 2 == 1 or vert % 2 == 1: print("NO") continue print("YES") grid = [['a'] * m for _ in range(n)] if n % 2 == 1: char = "x" for x in range(0, m, 2): grid[-1][x] = grid[-1][x + 1] = char if char == "x": char = "y" else: char = "x" if m % 2 == 1: char = "x" for y in range(0, n, 2): grid[y][-1] = grid[y + 1][-1] = char if char == "x": char = "y" else: char = "x" hchars = ["q", "w", "e", "r", "t", "z", "u", "i"] vchars = ["a", "s", "d", "f", "g", "h", "j", "k"] ci = 0 for y in range(n // 2): for x in range(m // 2): if hor: if y % 2 == 0 and x % 2 == 0: c1, c2 = hchars[0], hchars[1] elif y % 2 == 1 and x % 2 == 0: c1, c2 = hchars[2], hchars[3] elif y % 2 == 0 and x % 2 == 1: c1, c2 = hchars[4], hchars[5] elif y % 2 == 1 and x % 2 == 1: c1, c2 = hchars[6], hchars[7] grid[2 * y][2 * x] = grid[2 * y][2 * x + 1] = c1 grid[2 * y + 1][2 * x] = grid[2 * y + 1][2 * x + 1] = c2 hor -= 2 else: if y % 2 == 0 and x % 2 == 0: c1, c2 = vchars[0], vchars[1] elif y % 2 == 1 and x % 2 == 0: c1, c2 = vchars[2], vchars[3] elif y % 2 == 0 and x % 2 == 1: c1, c2 = vchars[4], vchars[5] elif y % 2 == 1 and x % 2 == 1: c1, c2 = vchars[6], vchars[7] grid[2 * y][2 * x] = grid[2 * y + 1][2 * x] = c1 grid[2 * y][2 * x + 1] = grid[2 * y + 1][2 * x + 1] = c2 for row in grid: print("".join(row))
Consider a sequence of integers a_1, a_2, …, a_n. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by 1 position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by 1. The indices of the elements after the move are recalculated. E. g. let the sequence be a=[3, 2, 2, 1, 5]. Let's select the element a_3=2 in a move. Then after the move the sequence will be equal to a=[3, 2, 1, 5], so the 3-rd element of the new sequence will be a_3=1 and the 4-th element will be a_4=5. You are given a sequence a_1, a_2, …, a_n and a number k. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least k elements that are equal to their indices, i. e. the resulting sequence b_1, b_2, …, b_m will contain at least k indices i such that b_i = i. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. Each test case consists of two consecutive lines. The first line contains two integers n and k (1 ≀ k ≀ n ≀ 2000). The second line contains a sequence of integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n). The numbers in the sequence are not necessarily different. It is guaranteed that the sum of n over all test cases doesn't exceed 2000. Output For each test case output in a single line: * -1 if there's no desired move sequence; * otherwise, the integer x (0 ≀ x ≀ n) β€” the minimum number of the moves to be made so that the resulting sequence will contain at least k elements that are equal to their indices. Example Input 4 7 6 1 1 2 3 4 5 6 5 2 5 1 3 2 3 5 2 5 5 5 5 4 8 4 1 2 3 3 2 2 5 5 Output 1 2 -1 2 Note In the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be [1, 2, 3, 4, 5, 6] and 6 elements will be equal to their indices. In the second test case there are two ways to get the desired result in 2 moves: the first one is to delete the 1-st and the 3-rd elements so that the sequence will be [1, 2, 3] and have 3 elements equal to their indices; the second way is to delete the 2-nd and the 3-rd elements to get the sequence [5, 2, 3] with 2 desired elements.
#include <bits/stdc++.h> using namespace std; const long long maxn = 2e5 + 50; long long n, dp[maxn], k, a[maxn], b[maxn], tp[maxn]; void solve() { for (long long i = 1; i <= n; i++) b[i] = i - a[i]; long long pos = 1, ans = 1e18; for (long long i = 1; i <= n; i++) { dp[i] = (b[i] >= 0); for (long long j = 1; j <= i - 1; j++) { if (b[i] >= 0 and a[i] > a[j] and b[j] <= b[i]) { dp[i] = max(dp[i], dp[j] + 1); } } if (dp[i] >= k and b[i] >= 0) { ans = min(ans, b[i]); } } if (ans != 1e18) cout << ans << '\n'; else cout << -1 << '\n'; } void input() { cin >> n >> k; for (long long i = 1; i <= n; i++) cin >> a[i], dp[i] = 0; } signed main() { ios_base::sync_with_stdio(false), cin.tie(0); ; long long tt; cin >> tt; while (tt--) { input(); solve(); } }
A tree is an undirected connected graph without cycles. You are given a tree of n vertices. Find the number of ways to choose exactly k vertices in this tree (i. e. a k-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer c such that for all u, v (u β‰  v, u, v are in selected vertices) d_{u,v}=c, where d_{u,v} is the distance from u to v). Since the answer may be very large, you need to output it modulo 10^9 + 7. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers n and k (2 ≀ k ≀ n ≀ 100) β€” the number of vertices in the tree and the number of vertices to be selected, respectively. Then n - 1 lines follow, each of them contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges. Output For each test case output in a separate line a single integer β€” the number of ways to select exactly k vertices so that for all pairs of selected vertices the distances between the vertices in the pairs are equal, modulo 10^9 + 7 (in other words, print the remainder when divided by 1000000007). Example Input 3 4 2 1 2 2 3 2 4 3 3 1 2 2 3 5 3 1 2 2 3 2 4 4 5 Output 6 0 1
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class T> vector<T> make_unique(vector<T> a) { sort((a).begin(), (a).end()); a.erase(unique((a).begin(), (a).end()), a.end()); return a; } const int INF = 1e9; const int MOD = 1e9 + 7; const int N = 111; int q[N], dist[N], root[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { int n, k; cin >> n >> k; vector<vector<int>> adj(n); for (int _ = 0; _ < (int)(n - 1); _++) { int u, v; cin >> u >> v; u--; v--; adj[u].push_back(v); adj[v].push_back(u); } if (k == 2) { cout << (long long int)n * (n - 1) / 2 << endl; continue; } long long int ans = 0; for (int s = 0; s < (int)(n); s++) { fill_n(dist, n, INF); int l = 0, r = 0; dist[s] = 0; q[r++] = s; while (l < r) { int u = q[l++]; for (auto v : adj[u]) { if (dist[v] > dist[u] + 1) { dist[v] = dist[u] + 1; root[v] = (u == s ? v : root[u]); q[r++] = v; } } } vector<map<int, int>> cnt(n); for (int u = 0; u < (int)(n); u++) cnt[dist[u]][root[u]]++; for (int d = 0; d < (int)(n); d++) { vector<int> poly(n + 1); poly[0] = 1; for (auto x : cnt[d]) { for (int i = (int)(n)-1; i >= ((int)0); i--) { poly[i + 1] += (long long int)x.second * poly[i] % MOD; if (poly[i + 1] >= MOD) poly[i + 1] -= MOD; } } ans += poly[k]; } } cout << ans % MOD << endl; } return 0; }
A string s of length n, consisting of lowercase letters of the English alphabet, is given. You must choose some number k between 0 and n. Then, you select k characters of s and permute them however you want. In this process, the positions of the other n-k characters remain unchanged. You have to perform this operation exactly once. For example, if s="andrea", you can choose the k=4 characters "a_d_ea" and permute them into "d_e_aa" so that after the operation the string becomes "dneraa". Determine the minimum k so that it is possible to sort s alphabetically (that is, after the operation its characters appear in alphabetical order). Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 40) β€” the length of the string. The second line of each test case contains the string s. It is guaranteed that s contains only lowercase letters of the English alphabet. Output For each test case, output the minimum k that allows you to obtain a string sorted alphabetically, through the operation described above. Example Input 4 3 lol 10 codeforces 5 aaaaa 4 dcba Output 2 6 0 4 Note In the first test case, we can choose the k=2 characters "_ol" and rearrange them as "_lo" (so the resulting string is "llo"). It is not possible to sort the string choosing strictly less than 2 characters. In the second test case, one possible way to sort s is to consider the k=6 characters "_o__force_" and rearrange them as "_c__efoor_" (so the resulting string is "ccdeefoors"). One can show that it is not possible to sort the string choosing strictly less than 6 characters. In the third test case, string s is already sorted (so we can choose k=0 characters). In the fourth test case, we can choose all k=4 characters "dcba" and reverse the whole string (so the resulting string is "abcd").
for _ in range(int(input())): n=int(input()) s=list(input().strip()) temp2=sorted(s) count=0 for i in range(n): if s[i]!=temp2[i]: count+=1 print(count)
The Olympic Games have just started and Federico is eager to watch the marathon race. There will be n athletes, numbered from 1 to n, competing in the marathon, and all of them have taken part in 5 important marathons, numbered from 1 to 5, in the past. For each 1≀ i≀ n and 1≀ j≀ 5, Federico remembers that athlete i ranked r_{i,j}-th in marathon j (e.g., r_{2,4}=3 means that athlete 2 was third in marathon 4). Federico considers athlete x superior to athlete y if athlete x ranked better than athlete y in at least 3 past marathons, i.e., r_{x,j}<r_{y,j} for at least 3 distinct values of j. Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes. Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1≀ n≀ 50 000) β€” the number of athletes. Then n lines follow, each describing the ranking positions of one athlete. The i-th of these lines contains the 5 integers r_{i,1},\,r_{i,2},\,r_{i,3},\,r_{i,4}, r_{i,5} (1≀ r_{i,j}≀ 50 000) β€” the ranking positions of athlete i in the past 5 marathons. It is guaranteed that, in each of the 5 past marathons, the n athletes have distinct ranking positions, i.e., for each 1≀ j≀ 5, the n values r_{1,j}, r_{2, j}, ..., r_{n, j} are distinct. It is guaranteed that the sum of n over all test cases does not exceed 50 000. Output For each test case, print a single integer β€” the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print -1. If there is more than such one athlete, print any of them. Example Input 4 1 50000 1 50000 50000 50000 3 10 10 20 30 30 20 20 30 10 10 30 30 10 20 20 3 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 6 9 5 3 7 1 7 4 1 6 8 5 6 7 3 2 6 7 8 8 6 4 2 2 4 5 8 3 6 9 4 Output 1 -1 1 5 Note Explanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal. Explanation of the second test case: There are n=3 athletes. * Athlete 1 is superior to athlete 2. Indeed athlete 1 ranks better than athlete 2 in the marathons 1, 2 and 3. * Athlete 2 is superior to athlete 3. Indeed athlete 2 ranks better than athlete 3 in the marathons 1, 2, 4 and 5. * Athlete 3 is superior to athlete 1. Indeed athlete 3 ranks better than athlete 1 in the marathons 3, 4 and 5. Explanation of the third test case: There are n=3 athletes. * Athlete 1 is superior to athletes 2 and 3. Since he is superior to all other athletes, he is likely to get the gold medal. * Athlete 2 is superior to athlete 3. * Athlete 3 is not superior to any other athlete. Explanation of the fourth test case: There are n=6 athletes. * Athlete 1 is superior to athletes 3, 4, 6. * Athlete 2 is superior to athletes 1, 4, 6. * Athlete 3 is superior to athletes 2, 4, 6. * Athlete 4 is not superior to any other athlete. * Athlete 5 is superior to athletes 1, 2, 3, 4, 6. Since he is superior to all other athletes, he is likely to get the gold medal. * Athlete 6 is only superior to athlete 4.
#include <bits/stdc++.h> using namespace std; const long long int M = 10000000007; long long int binarySearch(vector<long long int> arr, long long int l, long long int r, long long int x) { if (r >= l) { long long int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); return binarySearch(arr, mid + 1, r, x); } return -1; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); long long int tt, n, i, j, ans, cnt, flag; cin >> tt; while (tt--) { cin >> n; vector<vector<long long int> > v(n, (vector<long long int>(5))); for (i = 0; i < n; i++) { for (j = 0; j < 5; j++) { cin >> v[i][j]; } } if (n == 1) { cout << 1 << "\n"; continue; } ans = 0; for (i = 1; i < n; i++) { cnt = 0; for (j = 0; j < 5; j++) if (v[i][j] < v[ans][j]) cnt++; if (cnt >= 3) ans = i; } flag = 0; for (i = 0; i < n; i++) { cnt = 0; if (i == ans) continue; for (j = 0; j < 5; j++) if (v[i][j] < v[ans][j]) cnt++; if (cnt >= 3) { flag = 1; break; } } if (flag == 0) cout << ans + 1 << "\n"; else cout << -1 << "\n"; } return 0; }
On a circle lie 2n distinct points, with the following property: however you choose 3 chords that connect 3 disjoint pairs of points, no point strictly inside the circle belongs to all 3 chords. The points are numbered 1, 2, ..., 2n in clockwise order. Initially, k chords connect k pairs of points, in such a way that all the 2k endpoints of these chords are distinct. You want to draw n - k additional chords that connect the remaining 2(n - k) points (each point must be an endpoint of exactly one chord). In the end, let x be the total number of intersections among all n chords. Compute the maximum value that x can attain if you choose the n - k chords optimally. Note that the exact position of the 2n points is not relevant, as long as the property stated in the first paragraph holds. Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and k (1 ≀ n ≀ 100, 0 ≀ k ≀ n) β€” half the number of points and the number of chords initially drawn. Then k lines follow. The i-th of them contains two integers x_i and y_i (1 ≀ x_i, y_i ≀ 2n, x_i β‰  y_i) β€” the endpoints of the i-th chord. It is guaranteed that the 2k numbers x_1, y_1, x_2, y_2, ..., x_k, y_k are all distinct. Output For each test case, output the maximum number of intersections that can be obtained by drawing n - k additional chords. Example Input 4 4 2 8 2 1 5 1 1 2 1 2 0 10 6 14 6 2 20 9 10 13 18 15 12 11 7 Output 4 0 1 14 Note In the first test case, there are three ways to draw the 2 additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones): <image> We see that the third way gives the maximum number of intersections, namely 4. In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections. In the third test case, we can make at most one intersection by drawing chords 1-3 and 2-4, as shown below: <image>
def ch(x,y): if (y[0]<x[0]<y[1] and not(y[0]<x[1]<y[1])) or (y[0]<x[1]<y[1] and not(y[0]<x[0]<y[1])): return 1 return 0 t = int(input()) for i in range(t): n, k = [int(i) for i in input().split()] m = [] use = [0]*(2*n+1) for j in range(k): l,r = [int(i) for i in input().split()] if l>r: l,r = r,l use[l]=1 use[r]=1 m.append([l,r]) dontuse = [] for j in range(1, 2*n+1): if not(use[j]): dontuse.append(j) ll = len(dontuse) for j in range(ll//2): m.append([dontuse[j],dontuse[j+ll//2]]) m.sort() ans = 0 for j in range(n): for k in range(j+1, n): if ch(m[j],m[k]): ans+=1 print(ans)
You are given a sequence of n integers a_1, a_2, ..., a_n. Does there exist a sequence of n integers b_1, b_2, ..., b_n such that the following property holds? * For each 1 ≀ i ≀ n, there exist two (not necessarily distinct) indices j and k (1 ≀ j, k ≀ n) such that a_i = b_j - b_k. Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 10). The second line of each test case contains the n integers a_1, ..., a_n (-10^5 ≀ a_i ≀ 10^5). Output For each test case, output a line containing YES if a sequence b_1, ..., b_n satisfying the required property exists, and NO otherwise. Example Input 5 5 4 -7 -1 5 10 1 0 3 1 10 100 4 -3 2 10 2 9 25 -171 250 174 152 242 100 -205 -258 Output YES YES NO YES YES Note In the first test case, the sequence b = [-9, 2, 1, 3, -2] satisfies the property. Indeed, the following holds: * a_1 = 4 = 2 - (-2) = b_2 - b_5; * a_2 = -7 = -9 - (-2) = b_1 - b_5; * a_3 = -1 = 1 - 2 = b_3 - b_2; * a_4 = 5 = 3 - (-2) = b_4 - b_5; * a_5 = 10 = 1 - (-9) = b_3 - b_1. In the second test case, it is sufficient to choose b = [0], since a_1 = 0 = 0 - 0 = b_1 - b_1. In the third test case, it is possible to show that no sequence b of length 3 satisfies the property.
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import itertools t = int(input()) for _ in range(t): n = int(input()) A = list(map(int, input().split())) flag = False x = tuple([0]*n) for p in itertools.product(range(-1, 2), repeat=n): if p == x: continue s = 0 for i in range(n): s += p[i]*A[i] if s == 0: flag = True break if flag: print('YES') else: print('NO')
The numbers 1, 2, ..., n β‹… k are colored with n colors. These colors are indexed by 1, 2, ..., n. For each 1 ≀ i ≀ n, there are exactly k numbers colored with color i. Let [a, b] denote the interval of integers between a and b inclusive, that is, the set \\{a, a + 1, ..., b\}. You must choose n intervals [a_1, b_1], [a_2, b_2], ..., [a_n, b_n] such that: * for each 1 ≀ i ≀ n, it holds 1 ≀ a_i < b_i ≀ n β‹… k; * for each 1 ≀ i ≀ n, the numbers a_i and b_i are colored with color i; * each number 1 ≀ x ≀ n β‹… k belongs to at most \left⌈ (n)/(k - 1) \rightβŒ‰ intervals. One can show that such a family of intervals always exists under the given constraints. Input The first line contains two integers n and k (1 ≀ n ≀ 100, 2 ≀ k ≀ 100) β€” the number of colors and the number of occurrences of each color. The second line contains n β‹… k integers c_1, c_2, ..., c_{nk} (1 ≀ c_j ≀ n), where c_j is the color of number j. It is guaranteed that, for each 1 ≀ i ≀ n, it holds c_j = i for exactly k distinct indices j. Output Output n lines. The i-th line should contain the two integers a_i and b_i. If there are multiple valid choices of the intervals, output any. Examples Input 4 3 2 4 3 1 1 4 2 3 2 1 3 4 Output 4 5 1 7 8 11 6 12 Input 1 2 1 1 Output 1 2 Input 3 3 3 1 2 3 2 1 2 1 3 Output 6 8 3 7 1 4 Input 2 3 2 1 1 1 2 2 Output 2 3 5 6 Note In the first sample, each number can be contained in at most \left⌈ (4)/(3 - 1) \rightβŒ‰ = 2 intervals. The output is described by the following picture: <image> In the second sample, the only interval to be chosen is forced to be [1, 2], and each number is indeed contained in at most \left⌈ (1)/(2 - 1) \rightβŒ‰ = 1 interval. In the third sample, each number can be contained in at most \left⌈ (3)/(3 - 1) \rightβŒ‰ = 2 intervals. The output is described by the following picture: <image>
#include <bits/stdc++.h> using namespace std; const long long N = 105, K = 105; const long long oo = 1e18 + 7, mod = 1e9 + 7; long long n, k, a[N * K]; bool ok[N * K], ok2[N * K]; long long lst[N * K]; pair<long long, long long> ans[N * K]; long long sum[N * K]; void process() { cin >> n >> k; for (long long i = 1; i <= n * k; i++) cin >> a[i]; for (long long i = 1; i <= n; i++) ok[i] = 1; long long m = n; while (m) { for (long long i = 1; i <= n; i++) lst[i] = 0; long long ini = 0; for (long long i = 1; i <= n * k; i++) { if (!ok[a[i]]) continue; if (lst[a[i]]) { ini++; ans[a[i]] = {lst[a[i]], i}; ok[a[i]] = 0; for (long long j = 1; j <= n; j++) lst[j] = 0; if (ini == min(m, (k - 1))) break; } else lst[a[i]] = i; } assert(ini == min(m, (k - 1))); m -= min(m, k - 1); } for (long long i = 1; i <= n; i++) cout << ans[i].first << " " << ans[i].second << "\n"; } signed main() { ios_base::sync_with_stdio(0); process(); }
An ant moves on the real line with constant speed of 1 unit per second. It starts at 0 and always moves to the right (so its position increases by 1 each second). There are n portals, the i-th of which is located at position x_i and teleports to position y_i < x_i. Each portal can be either active or inactive. The initial state of the i-th portal is determined by s_i: if s_i=0 then the i-th portal is initially inactive, if s_i=1 then the i-th portal is initially active. When the ant travels through a portal (i.e., when its position coincides with the position of a portal): * if the portal is inactive, it becomes active (in this case the path of the ant is not affected); * if the portal is active, it becomes inactive and the ant is instantly teleported to the position y_i, where it keeps on moving as normal. How long (from the instant it starts moving) does it take for the ant to reach the position x_n + 1? It can be shown that this happens in a finite amount of time. Since the answer may be very large, compute it modulo 998 244 353. Input The first line contains the integer n (1≀ n≀ 2β‹… 10^5) β€” the number of portals. The i-th of the next n lines contains three integers x_i, y_i and s_i (1≀ y_i < x_i≀ 10^9, s_i∈\{0,1\}) β€” the position of the i-th portal, the position where the ant is teleported when it travels through the i-th portal (if it is active), and the initial state of the i-th portal. The positions of the portals are strictly increasing, that is x_1<x_2<β‹…β‹…β‹…<x_n. It is guaranteed that the 2n integers x_1, x_2, ..., x_n, y_1, y_2, ..., y_n are all distinct. Output Output the amount of time elapsed, in seconds, from the instant the ant starts moving to the instant it reaches the position x_n+1. Since the answer may be very large, output it modulo 998 244 353. Examples Input 4 3 2 0 6 5 1 7 4 0 8 1 1 Output 23 Input 1 454971987 406874902 1 Output 503069073 Input 5 243385510 42245605 0 644426565 574769163 0 708622105 208990040 0 786625660 616437691 0 899754846 382774619 0 Output 899754847 Input 5 200000000 100000000 1 600000000 400000000 0 800000000 300000000 0 900000000 700000000 1 1000000000 500000000 0 Output 3511295 Note Explanation of the first sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed 1 and the time spent during the movement is written above the arrow). $$$ 0 \stackrel{6}{\longrightarrow} 6 \leadsto 5 \stackrel{3}{\longrightarrow} 8 \leadsto 1 \stackrel{2}{\longrightarrow} 3 \leadsto 2 \stackrel{4}{\longrightarrow} 6 \leadsto 5 \stackrel{2}{\longrightarrow} 7 \leadsto 4 \stackrel{2}{\longrightarrow} 6 \leadsto 5 \stackrel{4}{\longrightarrow} 9 Notice that the total time is 6+3+2+4+2+2+4=23$$$. Explanation of the second sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed 1 and the time spent during the movement is written above the arrow). $$$ 0 \stackrel{454971987}{\longrightarrow} 454971987 \leadsto 406874902 \stackrel{48097086}{\longrightarrow} 454971988 Notice that the total time is 454971987+48097086=503069073$$$. Explanation of the third sample: Since all portals are initially off, the ant will not be teleported and will go straight from 0 to x_n+1=899754846+1=899754847.
#include <bits/stdc++.h> using namespace std; int n; const int mod = 998244353; struct wocao { int x, y, s; } a[200020]; int aa[400040]; map<int, int> mp; int bb[400040]; int c[400040]; int lowbit(int x) { return x & (-x); } int query(int x) { int ret = 0; while (x) (ret += c[x]) %= mod, x -= lowbit(x); return ret; } void add(int x, int y) { while (x <= n * 2) (c[x] += y) %= mod, x += lowbit(x); } int t[400040]; int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].s), aa[i * 2 - 1] = a[i].x, aa[i * 2] = a[i].y; sort(aa + 1, aa + n * 2 + 1); int tttt = 0; for (int i = 1; i <= 2 * n; i++) if (aa[i] != aa[i - 1]) mp[aa[i]] = ++tttt, bb[tttt] = aa[i]; for (int i = 1; i <= n; i++) a[i].x = mp[a[i].x], a[i].y = mp[a[i].y]; int temp; for (int i = n; i >= 1; i--) { if (a[i].s == 1) { t[i] = (query(a[i].x) + 1) % mod; } else { t[i] = query(a[i].x); } add(a[i].y, t[i]); } int ans = (bb[a[n].x] + 1) % mod; for (int i = 1; i <= n; i++) { long long l = bb[a[i].x] - bb[a[i].y]; (l *= t[i]) %= mod; (ans += l) %= mod; } cout << ans; return 0; }
Andrea has come up with what he believes to be a novel sorting algorithm for arrays of length n. The algorithm works as follows. Initially there is an array of n integers a_1, a_2, ..., a_n. Then, k steps are executed. For each 1≀ i≀ k, during the i-th step the subsequence of the array a with indexes j_{i,1}< j_{i,2}< ...< j_{i, q_i} is sorted, without changing the values with the remaining indexes. So, the subsequence a_{j_{i,1}}, a_{j_{i,2}}, ..., a_{j_{i,q_i}} is sorted and all other elements of a are left untouched. Andrea, being eager to share his discovery with the academic community, sent a short paper describing his algorithm to the journal "Annals of Sorting Algorithms" and you are the referee of the paper (that is, the person who must judge the correctness of the paper). You must decide whether Andrea's algorithm is correct, that is, if it sorts any array a of n integers. Input The first line contains two integers n and k (1≀ n≀ 40, 0≀ k≀ 10) β€” the length of the arrays handled by Andrea's algorithm and the number of steps of Andrea's algorithm. Then k lines follow, each describing the subsequence considered in a step of Andrea's algorithm. The i-th of these lines contains the integer q_i (1≀ q_i≀ n) followed by q_i integers j_{i,1},\,j_{i,2}, ..., j_{i,q_i} (1≀ j_{i,1}<j_{i,2}<β‹…β‹…β‹…<j_{i,q_i}≀ n) β€” the length of the subsequence considered in the i-th step and the indexes of the subsequence. Output If Andrea's algorithm is correct print ACCEPTED, otherwise print REJECTED. Examples Input 4 3 3 1 2 3 3 2 3 4 2 1 2 Output ACCEPTED Input 4 3 3 1 2 3 3 2 3 4 3 1 3 4 Output REJECTED Input 3 4 1 1 1 2 1 3 2 1 3 Output REJECTED Input 5 2 3 2 3 4 5 1 2 3 4 5 Output ACCEPTED Note Explanation of the first sample: The algorithm consists of 3 steps. The first one sorts the subsequence [a_1, a_2, a_3], the second one sorts the subsequence [a_2, a_3, a_4], the third one sorts the subsequence [a_1,a_2]. For example, if initially a=[6, 5, 6, 3], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) $$$ [{\color{red}6},{\color{red}5},{\color{red}6},3] β†’ [5, {\color{red}6}, {\color{red}6}, {\color{red}3}] β†’ [{\color{red}5}, {\color{red}3}, 6, 6] β†’ [3, 5, 6, 6] . One can prove that, for any initial array a, at the end of the algorithm the array a$$$ will be sorted. Explanation of the second sample: The algorithm consists of 3 steps. The first one sorts the subsequence [a_1, a_2, a_3], the second one sorts the subsequence [a_2, a_3, a_4], the third one sorts the subsequence [a_1,a_3,a_4]. For example, if initially a=[6, 5, 6, 3], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) $$$ [{\color{red}6},{\color{red}5},{\color{red}6},3] β†’ [5, {\color{red}6}, {\color{red}6}, {\color{red}3}] β†’ [{\color{red}5}, 3, {\color{red}6}, {\color{red}6}] β†’ [5, 3, 6, 6] . Notice that a=[6,5,6,3]$$$ is an example of an array that is not sorted by the algorithm. Explanation of the third sample: The algorithm consists of 4 steps. The first 3 steps do nothing because they sort subsequences of length 1, whereas the fourth step sorts the subsequence [a_1,a_3]. For example, if initially a=[5,6,4], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) $$$ [{\color{red}5},6,4] β†’ [5,{\color{red}6},4] β†’ [5,{\color{red}6},4] β†’ [{\color{red}5},6,{\color{red}4}]β†’ [4,6,5] . Notice that a=[5,6,4]$$$ is an example of an array that is not sorted by the algorithm. Explanation of the fourth sample: The algorithm consists of 2 steps. The first step sorts the subsequences [a_2,a_3,a_4], the second step sorts the whole array [a_1,a_2,a_3,a_4,a_5]. For example, if initially a=[9,8,1,1,1], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) $$$ [9,{\color{red}8},{\color{red}1},{\color{red}1},1] β†’ [{\color{red}9},{\color{red}1},{\color{red}1},{\color{red}8},{\color{red}1}] β†’ [1,1,1,8,9] . Since in the last step the whole array is sorted, it is clear that, for any initial array a, at the end of the algorithm the array a$$$ will be sorted.
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") using namespace std; using Int = long long; template <class T1, class T2> ostream &operator<<(ostream &os, const pair<T1, T2> &a) { return os << "(" << a.first << ", " << a.second << ")"; }; template <class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cerr << *i << " "; cerr << endl; } template <class T> bool chmin(T &t, const T &f) { if (t > f) { t = f; return true; } return false; } template <class T> bool chmax(T &t, const T &f) { if (t < f) { t = f; return true; } return false; } constexpr int MAX = 45; int N, K; int Q[MAX], J[MAX][MAX]; int k0s[MAX]; int as[MAX][MAX]; bool dfs(int k) { if (k == K) { for (int i = 0; i < N - 1; ++i) { if (as[K][i] > as[K][i + 1]) { return false; } } return true; } else { copy(as[k], as[k] + N, as[k + 1]); int cnt[3] = {}; for (int q = 0; q < Q[k]; ++q) { ++cnt[as[k][J[k][q]]]; } for (int q = 0; q < Q[k]; ++q) { as[k + 1][J[k][q]] = (q < cnt[0] + cnt[2]) ? 0 : 1; } for (int e = 0;; ++e) { if (!dfs(k + 1)) { return false; } if (e == cnt[2]) { break; } as[k + 1][J[k][cnt[0] + cnt[2] - 1 - e]] = 1; } } return true; } int main() { for (; ~scanf("%d%d", &N, &K);) { for (int k = 0; k < K; ++k) { scanf("%d", &Q[k]); for (int q = 0; q < Q[k]; ++q) { scanf("%d", &J[k][q]); --J[k][q]; } } bool ans = false; if (N == 1) { ans = true; } else { fill(k0s, k0s + N, -1); for (int k = K; k--;) { for (int q = 0; q < Q[k]; ++q) { k0s[J[k][q]] = k; } } bool ok = true; for (int i = 0; i < N; ++i) { ok = ok && (k0s[i] != -1); } if (ok) { fill(as[0], as[0] + N, 2); ans = dfs(0); } } puts(ans ? "ACCEPTED" : "REJECTED"); } return 0; }
You are the organizer of the famous "Zurich Music Festival". There will be n singers who will perform at the festival, identified by the integers 1, 2, ..., n. You must choose in which order they are going to perform on stage. You have m friends and each of them has a set of favourite singers. More precisely, for each 1≀ i≀ m, the i-th friend likes singers s_{i,1}, s_{i, 2}, ..., \,s_{i, q_i}. A friend of yours is happy if the singers he likes perform consecutively (in an arbitrary order). An ordering of the singers is valid if it makes all your friends happy. Compute the number of valid orderings modulo 998 244 353. Input The first line contains two integers n and m (1≀ n,\,m≀ 100) β€” the number of singers and the number of friends correspondingly. The i-th of the next m lines contains the integer q_i (1≀ q_i≀ n) β€” the number of favorite singers of the i-th friend – followed by the q_i integers s_{i,1}, s_{i, 2}, ..., \,s_{i, q_i} (1≀ s_{i,1}<s_{i,2}<β‹…β‹…β‹…<s_{i,q_i}≀ n) β€” the indexes of his favorite singers. Output Print the number of valid orderings of the singers modulo 998 244 353. Examples Input 3 1 2 1 3 Output 4 Input 5 5 2 1 2 2 2 3 2 3 4 2 4 5 2 1 5 Output 0 Input 100 1 1 50 Output 35305197 Input 5 1 5 1 2 3 4 5 Output 120 Input 2 5 1 2 1 2 1 2 1 1 1 1 Output 2 Input 11 4 5 4 5 7 9 11 2 2 10 2 9 11 7 1 2 3 5 8 10 11 Output 384 Note Explanation of the first sample: There are 3 singers and only 1 friend. The friend likes the two singers 1 and 3. Thus, the 4 valid orderings are: * 1 3 2 * 2 1 3 * 2 3 1 * 3 1 2 Explanation of the second sample: There are 5 singers and 5 friends. One can show that no ordering is valid. Explanation of the third sample: There are 100 singers and only 1 friend. The friend likes only singer 50, hence all the 100! possible orderings are valid. Explanation of the fourth sample: There are 5 singers and only 1 friend. The friend likes all the singers, hence all the 5!=120 possible orderings are valid.
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } int n, m, fac[1010]; class PQ_Tree { private: int n; public: struct node { vector<int> son; int type, op, siz, cnt; } t[1010 << 1]; int tot, rt; bool OK; bitset<1010> vis; void init(int _n) { tot = n = _n; rt = ++tot; for (int i = 1; i <= n; ++i) t[rt].son.push_back(i); } void dfs1(int u) { if (u <= n) return (void)(t[u].cnt = vis[u], t[u].siz = 1, t[u].op = vis[u] ? 2 : 1); t[u].op = t[u].siz = t[u].cnt = 0; for (auto v : t[u].son) { dfs1(v); t[u].cnt += t[v].cnt, t[u].siz += t[v].siz, t[u].op |= t[v].op; } } inline int GT(int u) { return t[u].cnt ? (t[u].cnt == t[u].siz ? 2 : 1) : 0; } int dfs2(int u, int lim) { if (!OK || t[u].op ^ 3) return u; vector<int> a[3]; for (auto v : t[u].son) { a[GT(v)].push_back(v); } if ((lim > 0) + a[1].size() >= 3) { OK = false; } if (!lim) { for (auto &v : t[u].son) { if (t[v].cnt == t[u].cnt) { v = dfs2(v, 0); return u; } } } if (t[u].type) { int now = 0; vector<int> S; if (GT(t[u].son[0]) == 2 || !GT(t[u].son.back())) { reverse(t[u].son.begin(), t[u].son.end()); } for (auto v : t[u].son) { int Type = GT(v); if (Type == 0) { S.push_back(v); now += now == 1; } else if (Type == 1) { if (now == 2) OK = false; ++now; int w = dfs2(v, 3 - now); S.insert(S.end(), t[w].son.begin(), t[w].son.end()); } else { S.push_back(v); now += !now; if (now == 2) OK = false; } } if (lim && now == 2) OK = false; if (lim == 1) reverse(S.begin(), S.end()); t[u].son = S; } else { int z = -1; if (a[2].size() == 1) z = a[2][0]; else if (a[2].size() > 1) z = ++tot, t[z].type = 0, t[z].son = a[2]; vector<int> S; if (!a[1].empty()) { int w = dfs2(a[1][0], 2); S.insert(S.end(), t[w].son.begin(), t[w].son.end()); } if (~z) S.push_back(z); if (a[1].size() > 1) { int w = dfs2(a[1][1], 1); S.insert(S.end(), t[w].son.begin(), t[w].son.end()); } if (a[0].empty()) { if (lim == 1) reverse(S.begin(), S.end()); t[u].type = 1, t[u].son = S; } else { if (lim) { t[u].son.clear(); t[u].type = 1; z = a[0][0]; if (a[0].size() > 1) { z = ++tot, t[z].type = 0, t[z].son = a[0]; } t[u].son.push_back(z); t[u].son.insert(t[u].son.end(), S.begin(), S.end()); if (lim == 1) reverse(t[u].son.begin(), t[u].son.end()); } else { z = S[0]; if (S.size() > 1) z = ++tot, t[z].son = S, t[z].type = 1; t[u].son = a[0], t[u].son.push_back(z); } } } return u; } bool Insert(const bitset<1010> &B) { vis = B; dfs1(rt); OK = true; rt = dfs2(rt, 0); return OK; } int calc(int u) { if (u <= n) return 1; int ans = t[u].type ? 2 : fac[t[u].son.size()]; for (auto v : t[u].son) ans = 1LL * ans * calc(v) % mod; return ans; } } T; int main() { n = read(), m = read(); fac[0] = 1; for (int i = 1; i <= n; ++i) { fac[i] = 1LL * fac[i - 1] * i % mod; } T.init(n); while (m--) { static bitset<1010> B; B.reset(); int k = read(); while (k--) B[read()] = 1; if (!T.Insert(B)) { puts("0"); return 0; } } printf("%d\n", T.calc(T.rt)); return 0; }
Let's define S(x) to be the sum of digits of number x written in decimal system. For example, S(5) = 5, S(10) = 1, S(322) = 7. We will call an integer x interesting if S(x + 1) < S(x). In each test you will be given one integer n. Your task is to calculate the number of integers x such that 1 ≀ x ≀ n and x is interesting. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” number of test cases. Then t lines follow, the i-th line contains one integer n (1 ≀ n ≀ 10^9) for the i-th test case. Output Print t integers, the i-th should be the answer for the i-th test case. Example Input 5 1 9 10 34 880055535 Output 0 1 1 3 88005553 Note The first interesting number is equal to 9.
x=int(input()) for i in range(x): y=int(input()) print((y+1)//10)
You have a string s and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i + 1. Of course, moving the chip to the right is impossible if it is already in the last position. After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i - 1. Of course, moving the chip to the left is impossible if it is already in the first position. When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if s is abcdef, you place the chip onto the 3-rd character, move it to the right 2 times and then move it to the left 3 times, you write down the string cdedcb. You are given two strings s and t. Your task is to determine whether it's possible to perform the described operations with s so that you write down the string t as a result. Input The first line contains one integer q (1 ≀ q ≀ 500) β€” the number of test cases. Each test case consists of two lines. The first line contains the string s (1 ≀ |s| ≀ 500), the second line contains the string t (1 ≀ |t| ≀ 2 β‹… |s| - 1). Both strings consist of lowercase English characters. It is guaranteed that the sum of |s| over all test cases does not exceed 500. Output For each test case, print "YES" if you can obtain the string t by performing the process mentioned in the statement with the string s, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer). Example Input 6 abcdef cdedcb aaa aaaaa aab baaa ab b abcdef abcdef ba baa Output YES YES NO YES YES NO Note Consider the examples. The first test case is described in the statement. In the second test case, you can place the chip on the 1-st position, move it twice to the right, and then move it twice to the left. In the fourth test case, you can place the chip on the 2-nd position, and then don't move it at all. In the fifth test case, you can place the chip on the 1-st position, move it 5 times to the right, and then finish the process.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Roy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BReverseString solver = new BReverseString(); solver.solve(1, in, out); out.close(); } static class BReverseString { private boolean goLeft(String s, String t, int i, int j) { if (j == t.length()) return true; if (i < 0 || i == s.length() || j < -1) return false; if (s.charAt(i) == t.charAt(j)) return goLeft(s, t, i - 1, j + 1); return false; } private boolean goRight(String s, String t, int i, int j) { if (j == t.length()) return true; if (i < 0 || i == s.length() || j < -1) return false; if (s.charAt(i) == t.charAt(j)) { return goRight(s, t, i + 1, j + 1) || goLeft(s, t, i - 1, j + 1); } else { return goLeft(s, t, i - 1, j - 1); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int tc = in.readInteger(); for (int cs = 1; cs <= tc; ++cs) { String s = in.readString(); String t = in.readString(); boolean foundMatch = false; for (int i = 0; i < s.length() && !foundMatch; i++) { if (s.charAt(i) == t.charAt(0)) { foundMatch = goRight(s, t, i, 0); } } if (foundMatch) out.printLine("YES"); else out.printLine("NO"); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInteger() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { this.print(objects); writer.println(); } public void close() { writer.flush(); writer.close(); } } }
Consider a simplified penalty phase at the end of a football match. A penalty phase consists of at most 10 kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the 7-th kick the first team has scored 1 goal, and the second team has scored 3 goals, the penalty phase ends β€” the first team cannot reach 3 goals. You know which player will be taking each kick, so you have your predictions for each of the 10 kicks. These predictions are represented by a string s consisting of 10 characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way: * if s_i is 1, then the i-th kick will definitely score a goal; * if s_i is 0, then the i-th kick definitely won't score a goal; * if s_i is ?, then the i-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase β€” you may know that some kick will/won't be scored, but the referee doesn't. Input The first line contains one integer t (1 ≀ t ≀ 1 000) β€” the number of test cases. Each test case is represented by one line containing the string s, consisting of exactly 10 characters. Each character is either 1, 0, or ?. Output For each test case, print one integer β€” the minimum possible number of kicks in the penalty phase. Example Input 4 1?0???1001 1111111111 ?????????? 0100000000 Output 7 10 6 9 Note Consider the example test: In the first test case, consider the situation when the 1-st, 5-th and 7-th kicks score goals, and kicks 2, 3, 4 and 6 are unsuccessful. Then the current number of goals for the first team is 3, for the second team is 0, and the referee sees that the second team can score at most 2 goals in the remaining kicks. So the penalty phase can be stopped after the 7-th kick. In the second test case, the penalty phase won't be stopped until all 10 kicks are finished. In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the 6-th kick, the first team has scored 0 goals and the second team has scored 3 goals, and the referee sees that the first team can score at most 2 goals in the remaining kicks. So, the penalty phase can be stopped after the 6-th kick. In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the 9-th kick.
#----------FASTIOSTART-----------# from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #----------FASTIOFINISH----------# import collections,string,bisect,re,random,queue,itertools,statistics,math from collections import * from bisect import * from string import * from itertools import * from statistics import * from math import * from re import * from queue import * #----------SASTA_STL-------------# # stack class Stack: def __init__(self):self.items = [] def push(self, item):self.items.append(item) def pop(self):return self.items.pop() def empty(self):return self.items == [] def size(self):return len(self.items) def at(self,idx): try:return self.items[idx] except:return -1 #priority_queue class priority_queue(object): def __init__(self):self.queue = [] def __str__(self):return ' '.join([str(i) for i in self.queue]) def empty(self):return len(self.queue) == 0 def push(self, data):self.queue.append(data) def pop(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() #----------SASTA_STL-------------# mod = int(1e9+7) imax = float("inf") imin = float("-inf") true = True false= False N = int(1e5) none = None inp = lambda : input() I = lambda : int(inp()) M = lambda : map(int,inp().split()) MS = lambda : map(str,inp().split()) S = lambda : list(MS()) L = lambda : list(M()) def IO(): try:sys.stdin = open('input.txt', 'r');sys.stdout = open('uttar.txt', 'w') except:pass IO() #----------TOTKA---------# def kabraji_ka_totka(): # totka hai dosto ! s=inp() team1=0; team2=0; res=9; res=10 maxa=0; maxb=0; mina=0 minb=0 for i in range(10): if(i&1): if(s[i]!="0"): maxb+=1 if(s[i]=="1"): minb+=1 else: if(s[i]!="0"): maxa+=1 if(s[i]=="1"): mina+=1 if(maxa-minb > (10-i)//2): res=i+1 break if(maxb-mina > (9-i)//2): res=i+1 break print(res) #----------TOTKA----------# if __name__ == '__main__': for i in range(I()):kabraji_ka_totka()
You are given two strings s and t, both consisting of lowercase English letters. You are going to type the string s character by character, from the first character to the last one. When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if s is "abcbd" and you press Backspace instead of typing the first and the fourth characters, you will get the string "bd" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if s is "abcaa" and you press Backspace instead of the last two letters, then the resulting text is "a". Your task is to determine whether you can obtain the string t, if you type the string s and press "Backspace" instead of typing several (maybe zero) characters of s. Input The first line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of test cases. The first line of each test case contains the string s (1 ≀ |s| ≀ 10^5). Each character of s is a lowercase English letter. The second line of each test case contains the string t (1 ≀ |t| ≀ 10^5). Each character of t is a lowercase English letter. It is guaranteed that the total number of characters in the strings over all test cases does not exceed 2 β‹… 10^5. Output For each test case, print "YES" if you can obtain the string t by typing the string s and replacing some characters with presses of "Backspace" button, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer). Example Input 4 ababa ba ababa bb aaa aaaa aababa ababa Output YES NO NO YES Note Consider the example test from the statement. In order to obtain "ba" from "ababa", you may press Backspace instead of typing the first and the fourth characters. There's no way to obtain "bb" while typing "ababa". There's no way to obtain "aaaa" while typing "aaa". In order to obtain "ababa" while typing "aababa", you have to press Backspace instead of typing the first character, then type all the remaining characters.
import java.util.Scanner; public class CF1553D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int test = scanner.nextInt(); scanner.nextLine(); StringBuilder result = new StringBuilder(); for (int t = 0; t < test; t++){ String first = scanner.nextLine(); String last = scanner.nextLine(); int p1 = first.length() - 1; int p2 = last.length() - 1; while (p1 >= 0 && p2 >= 0){ if (first.charAt(p1) == last.charAt(p2)){ p1--; p2--; }else{ p1 -= 2; } } result.append(p2 < 0 ? "YES" : "NO").append(System.lineSeparator()); } System.out.println(result); } }
An identity permutation of length n is an array [1, 2, 3, ..., n]. We performed the following operations to an identity permutation of length n: * firstly, we cyclically shifted it to the right by k positions, where k is unknown to you (the only thing you know is that 0 ≀ k ≀ n - 1). When an array is cyclically shifted to the right by k positions, the resulting array is formed by taking k last elements of the original array (without changing their relative order), and then appending n - k first elements to the right of them (without changing relative order of the first n - k elements as well). For example, if we cyclically shift the identity permutation of length 6 by 2 positions, we get the array [5, 6, 1, 2, 3, 4]; * secondly, we performed the following operation at most m times: pick any two elements of the array and swap them. You are given the values of n and m, and the resulting array. Your task is to find all possible values of k in the cyclic shift operation. Input The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case consists of two lines. The first line contains two integers n and m (3 ≀ n ≀ 3 β‹… 10^5; 0 ≀ m ≀ n/3). The second line contains n integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ n, each integer from 1 to n appears in this sequence exactly once) β€” the resulting array. The sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print the answer in the following way: * firstly, print one integer r (0 ≀ r ≀ n) β€” the number of possible values of k for the cyclic shift operation; * secondly, print r integers k_1, k_2, ..., k_r (0 ≀ k_i ≀ n - 1) β€” all possible values of k in increasing order. Example Input 4 4 1 2 3 1 4 3 1 1 2 3 3 1 3 2 1 6 0 1 2 3 4 6 5 Output 1 3 1 0 3 0 1 2 0 Note Consider the example: * in the first test case, the only possible value for the cyclic shift is 3. If we shift [1, 2, 3, 4] by 3 positions, we get [2, 3, 4, 1]. Then we can swap the 3-rd and the 4-th elements to get the array [2, 3, 1, 4]; * in the second test case, the only possible value for the cyclic shift is 0. If we shift [1, 2, 3] by 0 positions, we get [1, 2, 3]. Then we don't change the array at all (we stated that we made at most 1 swap), so the resulting array stays [1, 2, 3]; * in the third test case, all values from 0 to 2 are possible for the cyclic shift: * if we shift [1, 2, 3] by 0 positions, we get [1, 2, 3]. Then we can swap the 1-st and the 3-rd elements to get [3, 2, 1]; * if we shift [1, 2, 3] by 1 position, we get [3, 1, 2]. Then we can swap the 2-nd and the 3-rd elements to get [3, 2, 1]; * if we shift [1, 2, 3] by 2 positions, we get [2, 3, 1]. Then we can swap the 1-st and the 2-nd elements to get [3, 2, 1]; * in the fourth test case, we stated that we didn't do any swaps after the cyclic shift, but no value of cyclic shift could produce the array [1, 2, 3, 4, 6, 5].
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { FastReader s = new FastReader(); PrintWriter out = new PrintWriter(System.out); Main main = new Main(); int t = s.nextInt(); while(t > 0) { int n = s.nextInt(); int m = s.nextInt(); int[] arr = new int[n]; for(int i=0; i<n; i++) { arr[i] = s.nextInt(); } int[] res = main.check(arr, m); StringBuilder sb = new StringBuilder(); sb.append(res.length); for(int i=0; i<res.length; i++) { sb.append(" "); sb.append(res[i]); } out.println(sb.toString()); t--; } out.flush(); } private int[] check(int[] check, int m) { int n = check.length; List<Integer> ans = new ArrayList<>(); int[] cnt = new int[n]; for(int i=0; i<n; i++) { int offset = i+1-check[i]; if(offset < 0) offset += n; cnt[offset]++; } for(int i=0; i<n; i++) { if(cnt[i] + 2*m >= n) { if(n - getCycle(check, n-i) <= m) ans.add(i); } } int[] res = new int[ans.size()]; for(int i=0; i<res.length; i++) { res[i] = ans.get(i); } return res; } private int getCycle(int[] check, int s) { int n = check.length; boolean[] used = new boolean[n]; int ans = 0; for(int i = 0; i < n; i++) { if(used[i]) continue; int j = i; while(!used[j]) { used[j] = true; int sj = j-s; if(sj < 0) sj+=n; j = check[sj]-1; } ans++; } return ans; } } class FastReader { BufferedReader br; StringTokenizer st; InputStreamReader input;//no buffer public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public FastReader(boolean isBuffer) { if(!isBuffer){ input=new InputStreamReader(System.in); }else{ br=new BufferedReader(new InputStreamReader(System.in)); } } public boolean hasNext(){ try{ String s=br.readLine(); if(s==null){ return false; } st=new StringTokenizer(s); }catch(IOException e){ e.printStackTrace(); } return true; } public String next() { if(input!=null){ try { StringBuilder sb=new StringBuilder(); int ch=input.read(); while(ch=='\n'||ch=='\r'||ch==32){ ch=input.read(); } while(ch!='\n'&&ch!='\r'&&ch!=32){ sb.append((char)ch); ch=input.read(); } return sb.toString(); }catch (Exception e){ e.printStackTrace(); } } while(st==null || !st.hasMoreElements())//ε›žθ½¦οΌŒη©Ίθ‘Œζƒ…ε†΅ { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return (int)nextLong(); } public long nextLong() { try { if(input!=null){ long ret=0; int b=input.read(); while(b<'0'||b>'9'){ b=input.read(); } while(b>='0'&&b<='9'){ ret=ret*10+(b-'0'); b=input.read(); } return ret; } }catch (Exception e){ e.printStackTrace(); } return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
You have an array a consisting of n distinct positive integers, numbered from 1 to n. Define p_k as $$$p_k = βˆ‘_{1 ≀ i, j ≀ k} a_i mod a_j, where x \bmod y denotes the remainder when x is divided by y. You have to find and print p_1, p_2, \ldots, p_n$$$. Input The first line contains n β€” the length of the array (2 ≀ n ≀ 2 β‹… 10^5). The second line contains n space-separated distinct integers a_1, …, a_n (1 ≀ a_i ≀ 3 β‹… 10^5, a_i β‰  a_j if i β‰  j). Output Print n integers p_1, p_2, …, p_n. Examples Input 4 6 2 7 3 Output 0 2 12 22 Input 3 3 2 1 Output 0 3 5
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const long long MAX = 300010; const long long MOD = (long long)1e9 + 7; const long long INF = 1e9; const long long LLINF = 0x3f3f3f3f3f3f3f3f; const long double EPS = 1e-8; struct Segtree { vector<long long> seg, lazy; long long n, LOG; Segtree(long long n = 0) { this->n = n; LOG = ceil(log2(n)); seg.assign(2 * n, 0); lazy.assign(2 * n, 0); } long long merge(long long a, long long b) { return a + b; } void poe(long long p, long long x, long long tam, bool prop = 1) { seg[p] += x * tam; if (prop and p < n) lazy[p] += x; } void sobe(long long p) { for (long long tam = 2; p /= 2; tam *= 2) { seg[p] = merge(seg[2 * p], seg[2 * p + 1]); poe(p, lazy[p], tam, 0); } } void prop(long long p) { long long tam = 1 << (LOG - 1); for (long long s = LOG; s; s--, tam /= 2) { long long i = p >> s; if (lazy[i]) { poe(2 * i, lazy[i], tam); poe(2 * i + 1, lazy[i], tam); lazy[i] = 0; } } } void build() { for (long long i = n - 1; i; i--) seg[i] = merge(seg[2 * i], seg[2 * i + 1]); } long long query(long long a, long long b) { long long ret = 0; for (prop(a += n), prop(b += n); a <= b; ++a /= 2, --b /= 2) { if (a % 2 == 1) ret = merge(ret, seg[a]); if (b % 2 == 0) ret = merge(ret, seg[b]); } return ret; } void update(long long a, long long b, long long x) { long long a2 = a += n, b2 = b += n, tam = 1; for (; a <= b; ++a /= 2, --b /= 2, tam *= 2) { if (a % 2 == 1) poe(a, x, tam); if (b % 2 == 0) poe(b, x, tam); } sobe(a2), sobe(b2); } }; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; long long n; cin >> n; vector<long long> v(n); for (long long i = 0; i < (long long)n; i++) cin >> v[i]; Segtree st1 = Segtree(MAX); Segtree st2 = Segtree(MAX); Segtree st3 = Segtree(MAX); long long res = 0; for (long long k = 0; k < n; k++) { res += v[k] * st1.query(v[k], MAX - 1); res += v[k] * st1.query(1, v[k]) - st2.query(v[k], v[k]); res += st3.query(1, v[k]); res += st3.query(v[k], MAX - 1); for (long long m = 1; m * v[k] < MAX; m++) { res -= m * v[k] * st1.query(m * v[k], min((m + 1) * v[k] - 1, MAX - 1)); } st1.update(v[k], v[k], 1); for (long long m = 1; m * v[k] < MAX; m++) { st2.update(m * v[k], min((m + 1) * v[k] - 1, MAX - 1), m * v[k]); } st3.update(v[k], v[k], v[k]); cout << res << " "; } cout << '\n'; return 0; }
Consider a sequence of distinct integers a_1, …, a_n, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than 1. There are q queries, in each query, you want to get from one given node a_s to another a_t. In order to achieve that, you can choose an existing value a_i and create new value a_{n+1} = a_i β‹… (1 + a_i), with edges to all values that are not coprime with a_{n+1}. Also, n gets increased by 1. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that a_t is reachable from a_s? Queries are independent. In each query, you start with the initial sequence a given in the input. Input The first line contains two integers n and q (2 ≀ n ≀ 150 000, 1 ≀ q ≀ 300 000) β€” the size of the sequence and the number of queries. The second line contains n distinct integers a_1, a_2, …, a_n (2 ≀ a_i ≀ 10^6, a_i β‰  a_j if i β‰  j). The j-th of the following q lines contains two distinct integers s_j and t_j (1 ≀ s_j, t_j ≀ n, s_j β‰  t_j) β€” indices of nodes for j-th query. Output Print q lines. The j-th line should contain one integer: the minimum number of new nodes you create in order to move from a_{s_j} to a_{t_j}. Examples Input 3 3 2 10 3 1 2 1 3 2 3 Output 0 1 1 Input 5 12 3 8 7 6 25 1 2 1 3 1 4 1 5 2 1 2 3 2 4 2 5 3 1 3 2 3 4 3 5 Output 0 1 0 1 0 1 0 1 1 1 1 2 Note In the first example, you can first create new value 2 β‹… 3 = 6 or 10 β‹… 11 = 110 or 3 β‹… 4 = 12. None of that is needed in the first query because you can already get from a_1 = 2 to a_2 = 10. In the second query, it's optimal to first create 6 or 12. For example, creating 6 makes it possible to get from a_1 = 2 to a_3 = 3 with a path (2, 6, 3). <image> In the last query of the second example, we want to get from a_3 = 7 to a_5 = 25. One way to achieve that is to first create 6 β‹… 7 = 42 and then create 25 β‹… 26 = 650. The final graph has seven nodes and it contains a path from a_3 = 7 to a_5 = 25.
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def connected_components(n, graph): components, visited = [], [False] * n def dfs(start): component, stack = [], [start] while stack: start = stack[-1] if visited[start]: stack.pop() continue else: visited[start] = True component.append(start) for i in graph[start]: if not visited[i]: stack.append(i) return component for i in range(n): if not visited[i]: components.append(dfs(i)) return components def Sieve(limit=10 ** 6): """Uses Sieve algorithm and stores a factor of each number! If isPrime[i] = 1, the number 'i' is prime.""" isPrime = [1] * (limit + 1) isPrime[0] = isPrime[1] = 0 for i in range(2, limit + 1): if isPrime[i] != 1: continue for j in range(i * i, limit + 1, i): isPrime[j] = i return isPrime isPrime = Sieve(10**6 + 2) def prime_factors(n): """Returns prime factorisation of n!""" if n < 2: return [] result = [] while isPrime[n] > 1: y = isPrime[n] result += [y] while n % y == 0: n //= y if n != 1: result += [n] return result for _ in range(int(input()) if not True else 1): #n = int(input()) n, q = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() graph = [[] for i in range(n)] px = {} for i in range(n): for p in prime_factors(a[i]): if p not in px: px[p] = i else: graph[i] += [px[p]] graph[px[p]] += [i] cp = connected_components(n, graph) comp_num = [0] * n for i in range(1, len(cp)): for j in cp[i]: comp_num[j] = i st2 = set() for i in range(len(cp)): for j in cp[i]: y = set() for prime in prime_factors(a[j] + 1): if prime in px: st2.add((i, comp_num[px[prime]])) y.add(comp_num[px[prime]]) for y1 in y: for y2 in y: if y1 != y2: st2.add((y1, y2)) for __ in range(q): x, y = map(int, input().split()) x -= 1 y -= 1 if comp_num[x] == comp_num[y]: print(0) continue p, q = comp_num[x], comp_num[y] if (p, q) in st2 or (q, p) in st2: print(1) continue print(2)
You are given an array a consisting of n distinct elements and an integer k. Each element in the array is a non-negative integer not exceeding 2^k-1. Let's define the XOR distance for a number x as the value of $$$f(x) = min_{i = 1}^{n} min_{j = i + 1}^{n} |(a_i βŠ• x) - (a_j βŠ• x)|,$$$ where βŠ• denotes [the bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For every integer x from 0 to 2^k-1, you have to calculate f(x). Input The first line contains two integers n and k (1 ≀ k ≀ 19; 2 ≀ n ≀ 2^k). The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2^k-1). All these integers are distinct. Output Print 2^k integers. The i-th of them should be equal to f(i-1). Examples Input 3 3 6 0 3 Output 3 1 1 2 2 1 1 3 Input 3 4 13 4 2 Output 2 2 6 6 3 1 2 2 2 2 1 3 6 6 2 2 Note Consider the first example: * for x = 0, if we apply bitwise XOR to the elements of the array with x, we get the array [6, 0, 3], and the minimum absolute difference of two elements is 3; * for x = 1, if we apply bitwise XOR to the elements of the array with x, we get the array [7, 1, 2], and the minimum absolute difference of two elements is 1; * for x = 2, if we apply bitwise XOR to the elements of the array with x, we get the array [4, 2, 1], and the minimum absolute difference of two elements is 1; * for x = 3, if we apply bitwise XOR to the elements of the array with x, we get the array [5, 3, 0], and the minimum absolute difference of two elements is 2; * for x = 4, if we apply bitwise XOR to the elements of the array with x, we get the array [2, 4, 7], and the minimum absolute difference of two elements is 2; * for x = 5, if we apply bitwise XOR to the elements of the array with x, we get the array [3, 5, 6], and the minimum absolute difference of two elements is 1; * for x = 6, if we apply bitwise XOR to the elements of the array with x, we get the array [0, 6, 5], and the minimum absolute difference of two elements is 1; * for x = 7, if we apply bitwise XOR to the elements of the array with x, we get the array [1, 7, 4], and the minimum absolute difference of two elements is 3.
#include <bits/stdc++.h> using namespace std; template <class T> vector<T> readvec(int N) { vector<T> res(N); for (int i = 0; i < N; ++i) cin >> res[i]; return res; } void one() { int N, K; cin >> N >> K; vector<int> t = readvec<int>(N); vector<int> mins(1 << K, 1 << K); vector<vector<bool>> exists(K + 1); for (int i = 0; i <= K; ++i) { exists[i].resize(1 << i, false); } for (int j : t) exists[K][j] = true; for (int k = K - 1; k >= 0; --k) { for (int j = 0; j < (1 << k); ++j) { exists[k][j] = exists[k + 1][j * 2] | exists[k + 1][j * 2 + 1]; } } for (int k = 0; k < K; ++k) { for (int i = 0; i < (1 << (K - k - 1)); ++i) { int val = 1 << K; for (int j = 0; j < (1 << (k + 1)); j += 2) { if (exists[k + 1][j] && exists[k + 1][j + 1]) { int d = 1; int l = j; int r = j + 1; for (int cb = k + 1; cb < K; ++cb) { int currb = ((i >> (K - cb - 1)) & 1); d *= 2; l *= 2; r *= 2; if (exists[cb + 1][l ^ 1 ^ currb] && exists[cb + 1][r ^ currb]) { r ^= currb; l ^= currb ^ 1; d -= 1; } else if (exists[cb + 1][l] && exists[cb + 1][r]) { } else if (exists[cb + 1][l ^ 1] && exists[cb + 1][r ^ 1]) { l ^= 1; r ^= 1; } else { r ^= currb ^ 1; l ^= currb; d += 1; } } assert(d == (r ^ i) - (l ^ i)); val = min(val, d); } } for (int j = 0; j < (1 << k); ++j) { mins[(j << (K - k)) + i] = min(mins[(j << (K - k)) + i], val); mins[(j << (K - k)) + (1 << (K - k)) - 1 - i] = min(mins[(j << (K - k)) + (1 << (K - k)) - 1 - i], val); } } } for (int i = 0; i < (1 << K); ++i) { cout << mins[i] << " \n"[i + 1 == (1 << K)]; } } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); one(); cout << flush; }
For a permutation p of numbers 1 through n, we define a stair array a as follows: a_i is length of the longest segment of permutation which contains position i and is made of consecutive values in sorted order: [x, x+1, …, y-1, y] or [y, y-1, …, x+1, x] for some x ≀ y. For example, for permutation p = [4, 1, 2, 3, 7, 6, 5] we have a = [1, 3, 3, 3, 3, 3, 3]. You are given the stair array a. Your task is to calculate the number of permutations which have stair array equal to a. Since the number can be big, compute it modulo 998 244 353. Note that this number can be equal to zero. Input The first line of input contains integer n (1 ≀ n ≀ 10^5) β€” the length of a stair array a. The second line of input contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n). Output Print the number of permutations which have stair array equal to a. Since the number can be big, compute it modulo 998 244 353. Examples Input 6 3 3 3 1 1 1 Output 6 Input 7 4 4 4 4 3 3 3 Output 6 Input 1 1 Output 1 Input 8 2 2 2 2 2 2 1 1 Output 370 Input 4 3 2 3 1 Output 0
#include <bits/stdc++.h> using namespace std; template <typename T> void rd(T& x) { int f = 0, c; while (!isdigit(c = getchar())) f ^= !(c ^ 45); x = (c & 15); while (isdigit(c = getchar())) x = x * 10 + (c & 15); if (f) x = -x; } template <typename T> void pt(T x, int c = -1) { if (x < 0) putchar('-'), x = -x; if (x > 9) pt(x / 10); putchar(x % 10 + 48); if (c != -1) putchar(c); } const int P = 998244353; int ad(int k1, int k2) { return k1 += k2 - P, k1 += k1 >> 31 & P; } int su(int k1, int k2) { return k1 -= k2, k1 += k1 >> 31 & P; } int mu(int k1, int k2) { return 1LL * k1 * k2 % P; } void uad(int& k1, int k2) { k1 += k2 - P, k1 += k1 >> 31 & P; } void usu(int& k1, int k2) { k1 -= k2, k1 += k1 >> 31 & P; } template <typename... T> int ad(int k1, T... k2) { return ad(k1, ad(k2...)); } template <typename... T> void uad(int& k1, T... k2) { return uad(k1, ad(k2...)); } template <typename... T> void usu(int& k1, T... k2) { return usu(k1, ad(k2...)); } template <typename... T> int mu(int k1, T... k2) { return mu(k1, mu(k2...)); } int po(int k1, int k2) { int k3 = 1; for (; k2; k2 >>= 1, k1 = mu(k1, k1)) if (k2 & 1) k3 = mu(k3, k1); return k3; } namespace ntt { int base = 1, root = -1, maxbase = -1; std::vector<int> roots = {0, 1}, rev = {0, 1}; void init() { int tmp = P - 1; maxbase = 0; while (!(tmp & 1)) tmp >>= 1, maxbase++; root = 2; while (1) { if (po(root, 1 << maxbase) == 1 && po(root, 1 << (maxbase - 1)) != 1) break; root++; } } void ensure_base(int nbase) { if (maxbase == -1) init(); if (nbase <= base) return; rev.resize(1 << nbase); for (int i = 1; i < (1 << nbase); ++i) rev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (nbase - 1)); roots.resize(1 << nbase); while (base < nbase) { int z = po(root, 1 << (maxbase - base - 1)); for (int i = (1 << (base - 1)); i < (1 << base); ++i) roots[i << 1] = roots[i], roots[i << 1 | 1] = mu(roots[i], z); base++; } } void dft(std::vector<int>& a) { int n = a.size(), zeros = __builtin_ctz(n); ensure_base(zeros); int shift = base - zeros; for (int i = 0; i < n; ++i) if (i < (rev[i] >> shift)) std::swap(a[i], a[rev[i] >> shift]); for (int mid = 1; mid < n; mid <<= 1) for (int i = 0; i < n; i += (mid << 1)) for (int j = 0; j < mid; ++j) { int x = a[i + j], y = mu(a[i + j + mid], roots[mid + j]); a[i + j] = ad(x, y); a[i + j + mid] = su(x, y); } } std::vector<int> operator*(std::vector<int> a, std::vector<int> b) { if (((int)(a).size()) <= 50 && ((int)(b).size()) <= 50) { vector<int> c(((int)(a).size()) + ((int)(b).size()) - 1); for (int i = (0); i <= (((int)(a).size()) - 1); ++i) for (int j = (0); j <= (((int)(b).size()) - 1); ++j) uad(c[i + j], mu(a[i], b[j])); return c; } int need = a.size() + b.size() - 1, nbase = 0; while ((1 << nbase) < need) nbase++; ensure_base(nbase); int size = 1 << nbase; a.resize(size); b.resize(size); dft(a); dft(b); int inv = po(size, P - 2); for (int i = 0; i < size; ++i) a[i] = mu(a[i], mu(b[i], inv)); std::reverse(a.begin() + 1, a.end()); dft(a); a.resize(need); return a; } } // namespace ntt using ntt::operator*; vector<int> operator+(vector<int> a, vector<int> b) { if (a.size() < b.size()) a.resize(b.size()); for (int i = 0; i < (int)b.size(); i++) uad(a[i], b[i]); return a; } const int N = 1e5 + 5; vector<int> poly[N]; int a[N], b[N], fac[N], inv[N]; int n, m, tot; vector<int> solve(int l, int r) { if (l == r) return poly[l]; int mid = (l + r) >> 1; return solve(l, mid) * solve(mid + 1, r); } vector<int> f[N][2][2]; int vis[N][2][2]; vector<int> calc(int len, int l, int r) { if (len == 0) { vector<int> ans(1); ans[0] = 1; return ans; } if (len == 1) { vector<int> ans(2); ans[0] = 1; ans[1] = mu((P + 1) / 2, po(2, 2 - l - r)); return ans; } if (len == 2) { vector<int> ans(3); ans[0] = 1; ans[1] = 4 - l - r; ans[2] = mu((P + 1) / 2, po(2, 2 - l - r)); return ans; } if (vis[len][l][r]) return f[len][l][r]; vis[len][l][r] = 1; for (int i = 0; i <= 1; i++) { vector<int> L = calc((len - 1) >> 1, l, i); vector<int> R = calc(len >> 1, i, r); L = L * R; if (i == 1) { L.push_back(0); for (int i = (int)L.size() - 1; i >= 1; i--) L[i] = mu(L[i - 1], 2); L[0] = 0; } f[len][l][r] = f[len][l][r] + L; } return f[len][l][r]; } int main() { fac[0] = 1; for (int i = 1; i <= 100000; i++) fac[i] = mu(fac[i - 1], i); inv[100000] = po(fac[100000], P - 2); for (int i = 100000; i >= 1; i--) inv[i - 1] = mu(inv[i], i); rd(n); for (int i = 1; i <= n; i++) rd(a[i]); for (int l = 1, r; l <= n; l = r + 1) { int len = a[l]; r = l + len - 1; if (r > n) { pt(0, '\n'); return 0; } for (int i = l; i <= r; i++) { if (a[i] != len) { pt(0, '\n'); return 0; } } b[++m] = len; } for (int l = 1, r; l <= m; l = r + 1) { r = l; if (b[l] != 1) continue; while (r < m && b[r + 1] == 1) ++r; poly[++tot] = calc(r - l + (l != 1) + (r != m), l != 1, r != m); } for (int i = 1; i < m; i++) { if (b[i] != 1 && b[i + 1] != 1) { ++tot; poly[tot].resize(2); poly[tot][0] = 1; poly[tot][1] = (P + 1) / 2; } } int coef = 1; for (int i = 1; i <= m; i++) { if (b[i] != 1) { coef = mu(coef, 2); } } vector<int> res(1, 1); if (tot) res = solve(1, tot); int ans = 0; for (int i = 0; i < m; i++) { int now = mu(res[i], fac[m - i]); if (i & 1) ans = su(ans, now); else ans = ad(ans, now); } pt(mu(ans, coef), '\n'); return 0; }
You are given n integers a_1, a_2, …, a_n. Find the maximum value of max(a_l, a_{l + 1}, …, a_r) β‹… min(a_l, a_{l + 1}, …, a_r) over all pairs (l, r) of integers for which 1 ≀ l < r ≀ n. Input The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line of each test case contains a single integer n (2 ≀ n ≀ 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^6). It is guaranteed that the sum of n over all test cases doesn't exceed 3 β‹… 10^5. Output For each test case, print a single integer β€” the maximum possible value of the product from the statement. Example Input 4 3 2 4 3 4 3 2 3 1 2 69 69 6 719313 273225 402638 473783 804745 323328 Output 12 6 4761 381274500335 Note Let f(l, r) = max(a_l, a_{l + 1}, …, a_r) β‹… min(a_l, a_{l + 1}, …, a_r). In the first test case, * f(1, 2) = max(a_1, a_2) β‹… min(a_1, a_2) = max(2, 4) β‹… min(2, 4) = 4 β‹… 2 = 8. * f(1, 3) = max(a_1, a_2, a_3) β‹… min(a_1, a_2, a_3) = max(2, 4, 3) β‹… min(2, 4, 3) = 4 β‹… 2 = 8. * f(2, 3) = max(a_2, a_3) β‹… min(a_2, a_3) = max(4, 3) β‹… min(4, 3) = 4 β‹… 3 = 12. So the maximum is f(2, 3) = 12. In the second test case, the maximum is f(1, 2) = f(1, 3) = f(2, 3) = 6.
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // solution int t = sc.nextInt(); while (t != 0) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); } int minIndex = 0; int maxIndex = 1; if (arr[1] < arr[0]) { minIndex = 1; maxIndex = 0; } long res = (long)arr[minIndex] * (long)arr[maxIndex]; /*for (int i = 2; i < n; ++i) { if (arr[i] > arr[minIndex] && arr[i] < arr[maxIndex]) { minIndex = i; } else if (arr[i] >= arr[maxIndex]) { maxIndex = i; } res = Math.max(res, (long)arr[minIndex] * (long)arr[maxIndex]); } */ for (int i = 2; i < n; ++i) { res = Math.max(res, (long)arr[i] * (long)arr[i - 1]); } out.println(res); --t; } out.close(); } // ----------------------------------------------------------------- public static MyScanner sc; public static PrintWriter out; public static 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; } } }
You are given n integers a_1, a_2, …, a_n and an integer k. Find the maximum value of i β‹… j - k β‹… (a_i | a_j) over all pairs (i, j) of integers with 1 ≀ i < j ≀ n. Here, | is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Input The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line of each test case contains two integers n (2 ≀ n ≀ 10^5) and k (1 ≀ k ≀ min(n, 100)). The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ n). It is guaranteed that the sum of n over all test cases doesn't exceed 3 β‹… 10^5. Output For each test case, print a single integer β€” the maximum possible value of i β‹… j - k β‹… (a_i | a_j). Example Input 4 3 3 1 1 3 2 2 1 2 4 3 0 1 2 3 6 6 3 2 0 0 5 6 Output -1 -4 3 12 Note Let f(i, j) = i β‹… j - k β‹… (a_i | a_j). In the first test case, * f(1, 2) = 1 β‹… 2 - k β‹… (a_1 | a_2) = 2 - 3 β‹… (1 | 1) = -1. * f(1, 3) = 1 β‹… 3 - k β‹… (a_1 | a_3) = 3 - 3 β‹… (1 | 3) = -6. * f(2, 3) = 2 β‹… 3 - k β‹… (a_2 | a_3) = 6 - 3 β‹… (1 | 3) = -3. So the maximum is f(1, 2) = -1. In the fourth test case, the maximum is f(3, 4) = 12.
for _ in range(int(input())): n,k = map( int, input().split(' ') ) arr = [int(w) for w in input().split(' ')] ans = -10**18 temp =[] cnt = 0 for i in range(n-1,-1,-1): temp.append( (arr[i],i) ) cnt += 1 if cnt==300: break for i in range(len(temp)): for j in range(i+1,len(temp)): u1,v1 = temp[i] u2,v2 = temp[j] ans = max(ans , (v1+1)*(v2+1) - k*(u1|u2) ) print(ans)
You are given two integers n and m. Find the \operatorname{MEX} of the sequence n βŠ• 0, n βŠ• 1, …, n βŠ• m. Here, βŠ• is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). \operatorname{MEX} of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, \operatorname{MEX}(0, 1, 2, 4) = 3, and \operatorname{MEX}(1, 2021) = 0. Input The first line contains a single integer t (1 ≀ t ≀ 30 000) β€” the number of test cases. The first and only line of each test case contains two integers n and m (0 ≀ n, m ≀ 10^9). Output For each test case, print a single integer β€” the answer to the problem. Example Input 5 3 5 4 6 3 2 69 696 123456 654321 Output 4 3 0 640 530866 Note In the first test case, the sequence is 3 βŠ• 0, 3 βŠ• 1, 3 βŠ• 2, 3 βŠ• 3, 3 βŠ• 4, 3 βŠ• 5, or 3, 2, 1, 0, 7, 6. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 4. In the second test case, the sequence is 4 βŠ• 0, 4 βŠ• 1, 4 βŠ• 2, 4 βŠ• 3, 4 βŠ• 4, 4 βŠ• 5, 4 βŠ• 6, or 4, 5, 6, 7, 0, 1, 2. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 3. In the third test case, the sequence is 3 βŠ• 0, 3 βŠ• 1, 3 βŠ• 2, or 3, 2, 1. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 0.
import sys input = sys.stdin.readline # sys.setrecursionlimit(400000) def I(): return input().strip() def II(): return int(input().strip()) def LI(): return [*map(int, input().strip().split())] import copy, string, math, time, functools, random, fractions from heapq import heappush, heappop, heapify from bisect import bisect_left, bisect_right from collections import deque, defaultdict, Counter, OrderedDict from itertools import permutations, combinations, groupby from operator import itemgetter for _ in range(II()): a, b = LI() if a > b: print(0) continue get_bin = lambda x, n: format(x, 'b').zfill(n) A, B = get_bin(a, 32), get_bin(b + 1, 32) ans = [0] * 32 for i in range(32): if A[i] == B[i]: continue if A[i] == '1': break ans[i] = 1 print(int(''.join([str(x) for x in ans]), 2))
You are given an integer n. Find any string s of length n consisting only of English lowercase letters such that each non-empty substring of s occurs in s an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input The first line contains a single integer t (1 ≀ t ≀ 500) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 10^5). It is guaranteed that the sum of n over all test cases doesn't exceed 3 β‹… 10^5. Output For each test case, print a single line containing the string s. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints. Example Input 4 3 5 9 19 Output abc diane bbcaabbba youarethecutestuwuu Note In the first test case, each substring of "abc" occurs exactly once. In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs 5 times, "a" and "bb" occur 3 times each, and each of the remaining substrings occurs exactly once.
#include <bits/stdc++.h> using namespace std; int main() { int T; scanf("%d", &T); while (T--) { int N; scanf("%d", &N); if (N < 20) for (int i = 0; i < N; ++i) putchar('a' + i); else { if (N & 1) { putchar('c'); --N; } for (int i = 0; i < N / 2; ++i) putchar('a'); putchar('b'); for (int i = 1; i < N / 2; ++i) putchar('a'); } puts(""); } return 0; }
You are given a tree with n nodes. As a reminder, a tree is a connected undirected graph without cycles. Let a_1, a_2, …, a_n be a sequence of integers. Perform the following operation exactly n times: * Select an unerased node u. Assign a_u := number of unerased nodes adjacent to u. Then, erase the node u along with all edges that have it as an endpoint. For each integer k from 1 to n, find the number, modulo 998 244 353, of different sequences a_1, a_2, …, a_n that satisfy the following conditions: * it is possible to obtain a by performing the aforementioned operations exactly n times in some order. * \operatorname{gcd}(a_1, a_2, …, a_n) = k. Here, \operatorname{gcd} means the greatest common divisor of the elements in a. Input The first line contains a single integer t (1 ≀ t ≀ 10 000) β€” the number of test cases. The first line of each test case contains a single integer n (2 ≀ n ≀ 10^5). Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n) indicating there is an edge between vertices u and v. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of n over all test cases doesn't exceed 3 β‹… 10^5. Output For each test case, print n integers in a single line, where for each k from 1 to n, the k-th integer denotes the answer when \operatorname{gcd} equals to k. Example Input 2 3 2 1 1 3 2 1 2 Output 3 1 0 2 0 Note In the first test case, <image> * If we delete the nodes in order 1 β†’ 2 β†’ 3 or 1 β†’ 3 β†’ 2, then the obtained sequence will be a = [2, 0, 0] which has \operatorname{gcd} equals to 2. * If we delete the nodes in order 2 β†’ 1 β†’ 3, then the obtained sequence will be a = [1, 1, 0] which has \operatorname{gcd} equals to 1. * If we delete the nodes in order 3 β†’ 1 β†’ 2, then the obtained sequence will be a = [1, 0, 1] which has \operatorname{gcd} equals to 1. * If we delete the nodes in order 2 β†’ 3 β†’ 1 or 3 β†’ 2 β†’ 1, then the obtained sequence will be a = [0, 1, 1] which has \operatorname{gcd} equals to 1. Note that here we are counting the number of different sequences, not the number of different orders of deleting nodes.
import sys input = lambda: sys.stdin.readline().rstrip("\r\n") MOD = 998244353 t = int(input()) while t > 0: t -= 1 n = int(input()) g = [[] for i in range(n)] for i in range(n - 1): x, y = map(int, input().split()) g[x - 1] += [y - 1] g[y - 1] += [x - 1] f = [0] * n parent = [0] * n f[1] = pow(2, n - 1, MOD) order = [0] for v in order: for u in g[v]: if u != parent[v]: parent[u] = v order += [u] def dfs(k): size = [0] * n for v in reversed(order): if size[v] % k == 0: if v != 0: size[parent[v]] += 1 elif v == 0 or (size[v] + 1) % k != 0: return False return True for i in range(2, n): if (n - 1) % i == 0: f[i] = int(dfs(i)) h = [0] * (n + 1) for i in range(n - 1, 0, -1): h[i] = f[i] for j in range(i * 2, n, i): h[i] -= h[j] print(*(x for x in h[1:n + 1]))
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of 6 slices, medium ones consist of 8 slices, and large pizzas consist of 10 slices each. Baking them takes 15, 20 and 25 minutes, respectively. Petya's birthday is today, and n of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order. Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least n slices in total. For example: * if 12 friends come to Petya's birthday, he has to order pizzas containing at least 12 slices in total. He can order two small pizzas, containing exactly 12 slices, and the time to bake them is 30 minutes; * if 15 friends come to Petya's birthday, he has to order pizzas containing at least 15 slices in total. He can order a small pizza and a large pizza, containing 16 slices, and the time to bake them is 40 minutes; * if 300 friends come to Petya's birthday, he has to order pizzas containing at least 300 slices in total. He can order 15 small pizzas, 10 medium pizzas and 13 large pizzas, in total they contain 15 β‹… 6 + 10 β‹… 8 + 13 β‹… 10 = 300 slices, and the total time to bake them is 15 β‹… 15 + 10 β‹… 20 + 13 β‹… 25 = 750 minutes; * if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is 15 minutes. Input The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of testcases. Each testcase consists of a single line that contains a single integer n (1 ≀ n ≀ 10^{16}) β€” the number of Petya's friends. Output For each testcase, print one integer β€” the minimum number of minutes that is needed to bake pizzas containing at least n slices in total. Example Input 6 12 15 300 1 9999999999999999 3 Output 30 40 750 15 25000000000000000 15
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int in; cin >> in; for (int i = 0; i < in; i++) solve(); return 0; } void solve() { long long n, time, tempTime; cin >> n; if (n < 7) time = 15; else { tempTime = n * 2.5; if (tempTime % 5) time = (tempTime / 5) * 5 + 5; else time = tempTime; } cout << time << '\n'; }
You have an axis-aligned rectangle room with width W and height H, so the lower left corner is in point (0, 0) and the upper right corner is in (W, H). There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in (x_1, y_1), and the upper right corner in (x_2, y_2). You want to place another rectangular table in this room with width w and height h with the width of the table parallel to the width of the room. The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though). You can't rotate any of the tables, but you can move the first table inside the room. <image> Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one? Input The first line contains the single integer t (1 ≀ t ≀ 5000) β€” the number of the test cases. The first line of each test case contains two integers W and H (1 ≀ W, H ≀ 10^8) β€” the width and the height of the room. The second line contains four integers x_1, y_1, x_2 and y_2 (0 ≀ x_1 < x_2 ≀ W; 0 ≀ y_1 < y_2 ≀ H) β€” the coordinates of the corners of the first table. The third line contains two integers w and h (1 ≀ w ≀ W; 1 ≀ h ≀ H) β€” the width and the height of the second table. Output For each test case, print the minimum distance you should move the first table, or -1 if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Example Input 5 8 5 2 1 7 4 4 2 5 4 2 2 5 4 3 3 1 8 0 3 1 6 1 5 8 1 3 0 6 1 5 1 8 10 4 5 7 8 8 5 Output 1.000000000 -1 2.000000000 2.000000000 0.000000000 Note The configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by (0, -1), so the lower left corner will move from (2, 1) to (2, 0). Then you can place the second table at (0, 3)-(4, 5). In the second test case, there is no way to fit both tables in the room without intersecting. In the third test case, you can move the first table by (0, 2), so the lower left corner will move from (0, 3) to (0, 5).
from collections import * from math import * TT=int(input()) for y in range(TT): #n=int(input()) n,m=map(int,input().split()) #lst=list(map(int,input().split())) #s=input() x1,y1,x2,y2=map(int,input().split()) w,h=map(int,input().split()) if ((x2-x1)+w)<=n: if ((y2-y1)+h)<=m: rh=max(m-y2,y1) r1=max(h-rh,0) rw=max(n-x2,x1) r2=max(w-rw,0) print(min(r1,r2)) else: rw=max(n-x2,x1) r2=max(w-rw,0) print(r2) else: if ((y2-y1)+h)<=m: rh=max(m-y2,y1) r1=max(h-rh,0) print(r1) else: print('-1')
Alice and Bob are playing a game on a matrix, consisting of 2 rows and m columns. The cell in the i-th row in the j-th column contains a_{i, j} coins in it. Initially, both Alice and Bob are standing in a cell (1, 1). They are going to perform a sequence of moves to reach a cell (2, m). The possible moves are: * Move right β€” from some cell (x, y) to (x, y + 1); * Move down β€” from some cell (x, y) to (x + 1, y). First, Alice makes all her moves until she reaches (2, m). She collects the coins in all cells she visit (including the starting cell). When Alice finishes, Bob starts his journey. He also performs the moves to reach (2, m) and collects the coins in all cells that he visited, but Alice didn't. The score of the game is the total number of coins Bob collects. Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally? Input The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of the testcase contains a single integer m (1 ≀ m ≀ 10^5) β€” the number of columns of the matrix. The i-th of the next 2 lines contain m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (1 ≀ a_{i,j} ≀ 10^4) β€” the number of coins in the cell in the i-th row in the j-th column of the matrix. The sum of m over all testcases doesn't exceed 10^5. Output For each testcase print a single integer β€” the score of the game if both players play optimally. Example Input 3 3 1 3 7 3 5 1 3 1 3 9 3 5 1 1 4 7 Output 7 8 0 Note The paths for the testcases are shown on the following pictures. Alice's path is depicted in red and Bob's path is depicted in blue. <image>
#include <bits/stdc++.h> using namespace std; int n; long long a[3][100011], sum[3][100011]; void solve() { cin >> n; for (int i = 1; i <= 2; i++) for (int j = 1; j <= n; j++) cin >> a[i][j], sum[i][j] = 0; sum[2][1] = a[2][1]; sum[1][1] = a[1][1]; for (int i = 2; i <= n; i++) sum[1][i] = sum[1][i - 1] + a[1][i], sum[2][i] = sum[2][i - 1] + a[2][i]; long long ans = 1e18; for (int i = 1; i <= n; i++) { ans = min(ans, max(sum[1][n] - sum[1][i], sum[2][i - 1])); } cout << ans << endl; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
Let's call the string beautiful if it does not contain a substring of length at least 2, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not. Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first 3 letters of the Latin alphabet (in lowercase). You are given a string s of length n, each character of the string is one of the first 3 letters of the Latin alphabet (in lowercase). You have to answer m queries β€” calculate the cost of the substring of the string s from l_i-th to r_i-th position, inclusive. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the length of the string s and the number of queries. The second line contains the string s, it consists of n characters, each character one of the first 3 Latin letters. The following m lines contain two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ n) β€” parameters of the i-th query. Output For each query, print a single integer β€” the cost of the substring of the string s from l_i-th to r_i-th position, inclusive. Example Input 5 4 baacb 1 3 1 5 4 5 2 3 Output 1 2 0 1 Note Consider the queries of the example test. * in the first query, the substring is baa, which can be changed to bac in one operation; * in the second query, the substring is baacb, which can be changed to cbacb in two operations; * in the third query, the substring is cb, which can be left unchanged; * in the fourth query, the substring is aa, which can be changed to ba in one operation.
import sys input=sys.stdin output=sys.stdout inputs=input.readline().strip().split() N=int(inputs[0]) M=int(inputs[1]) S=input.readline().strip() SL=['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] CL=[[0]*(N+1) for x in range(6)] #def check_beautiful(substring): # total=len(substring) # for i in SL: # subtotal=0 # count=0 # for j in range(len(substring)): # if substring[j] != i[count]: # subtotal+=1 # count=(count+1) % 3 # if subtotal < total: # total=subtotal # return total for i in range(6): subtotal=0 substring=SL[i] subCL=CL[i] for j in range(N): if S[j] != substring[j % 3]: subtotal+=1 subCL[j+1]=subtotal for i in range(M): y=input.readline().strip().split() start=int(y[0]) end=int(y[1]) total=N for j in range(6): a=CL[j][end]-CL[j][start-1] if a<total: total=a print(total)
You are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i. You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point m starting from point 1 in arbitrary number of moves. The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset. In every test there exists at least one good subset. Input The first line contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^6) β€” the number of segments and the number of integer points. Each of the next n lines contains three integers l_i, r_i and w_i (1 ≀ l_i < r_i ≀ m; 1 ≀ w_i ≀ 10^6) β€” the description of the i-th segment. In every test there exists at least one good subset. Output Print a single integer β€” the minimum cost of a good subset. Examples Input 5 12 1 5 5 3 4 10 4 10 6 11 12 5 10 12 3 Output 3 Input 1 10 1 10 23 Output 0
#include <bits/stdc++.h> using namespace std; int n, m; struct Seg { int l; int r; int w; }; vector<int> segTree; vector<int> lazyTree; void updateSegT(int node, int st, int end, int l, int r, int val) { if (l > r) return; if (lazyTree[node]) { lazyTree[2 * node] += lazyTree[node]; lazyTree[2 * node + 1] += lazyTree[node]; segTree[node] += lazyTree[node]; lazyTree[node] = 0; } if (l > end || r < st) return; if (st >= l && end <= r) { segTree[node] += val; lazyTree[2 * node] += val; lazyTree[2 * node + 1] += val; } else { int mid = (st + end) / 2; updateSegT(2 * node, st, mid, l, r, val); updateSegT(2 * node + 1, mid + 1, end, l, r, val); segTree[node] = min(segTree[2 * node], segTree[2 * node + 1]); } } vector<Seg> segs; int main() { cin >> n >> m; m--; int nm = 1 << (int)ceil(log2(m)); segTree.resize(nm * 2); lazyTree.resize(nm * 2 * 2); int l, r, w; for (int(i) = (0); (i) < (n); ++(i)) { cin >> l >> r >> w; segs.push_back({l, r - 1, w}); } sort(segs.begin(), segs.end(), [](const Seg& a, const Seg& b) { return (a.w < b.w); }); updateSegT(1, 1, nm, m + 1, nm, 3000001); int ans = INT_MAX; for (int p1 = 0, p2 = 0; p1 < n; p1++) { updateSegT(1, 1, nm, segs[p1].l, segs[p1].r, 1); if (!segTree[1]) continue; while (segTree[1]) { updateSegT(1, 1, nm, segs[p2].l, segs[p2].r, -1); p2++; } ans = min(ans, segs[p1].w - segs[p2 - 1].w); } cout << ans; return 0; }
You have an undirected graph consisting of n vertices with weighted edges. A simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of edges it consists of. Let's say the graph is good if all its simple cycles have weight 1. A graph is bad if it's not good. Initially, the graph is empty. Then q queries follow. Each query has the next type: * u v x β€” add edge between vertices u and v of weight x if it doesn't make the graph bad. For each query print, was the edge added or not. Input The first line contains two integers n and q (3 ≀ n ≀ 3 β‹… 10^5; 1 ≀ q ≀ 5 β‹… 10^5) β€” the number of vertices and queries. Next q lines contain queries β€” one per line. Each query contains three integers u, v and x (1 ≀ u, v ≀ n; u β‰  v; 0 ≀ x ≀ 1) β€” the vertices of the edge and its weight. It's guaranteed that there are no multiple edges in the input. Output For each query, print YES if the edge was added to the graph, or NO otherwise (both case-insensitive). Example Input 9 12 6 1 0 1 3 1 3 6 0 6 2 0 6 4 1 3 4 1 2 4 0 2 5 0 4 5 0 7 8 1 8 9 1 9 7 0 Output YES YES YES YES YES NO YES YES NO YES YES NO
#include <bits/stdc++.h> struct disjoin_set_union { std::vector<int> parent; std::vector<int> rank; disjoin_set_union(int n = 0) : parent(n), rank(n, 1) { std::iota(parent.begin(), parent.end(), 0); } int root(int v) { return (v ^ parent[v]) ? parent[v] = root(parent[v]) : v; } bool unite(int v, int u) { v = root(v), u = root(u); if (v == u) return false; if (rank[v] < rank[u]) std::swap(v, u); rank[v] += rank[u]; parent[u] = v; return true; } }; struct link_cut { struct node { int parent; std::array<int, 2> sons; bool inv; int size; int value, tot; node() : parent(-1), sons({-1, -1}), inv(false), size(1), value(0), tot(0) {} }; std::vector<node> tree; void push(int v) { if (tree[v].inv) { tree[v].inv = false; std::swap(tree[v].sons[0], tree[v].sons[1]); for (const auto u : tree[v].sons) if (u != -1) tree[u].inv ^= 1; } } void relax(int v) { push(v); tree[v].size = 1; for (const auto x : tree[v].sons) if (x != -1) tree[v].size += tree[x].size; tree[v].tot = tree[v].value; for (const auto x : tree[v].sons) if (x != -1) tree[v].tot ^= tree[x].tot; } void rotate(int v) { int u = tree[v].parent, w = tree[u].parent; push(u), push(v); tree[v].parent = w; if (w != -1) for (auto &x : tree[w].sons) if (x == u) x = v; int i = tree[u].sons[1] == v; tree[u].sons[i] = tree[v].sons[i ^ 1]; if (tree[v].sons[i ^ 1] != -1) tree[tree[v].sons[i ^ 1]].parent = u; tree[v].sons[i ^ 1] = u; tree[u].parent = v; relax(u), relax(v); } bool is_root(int v) { return tree[v].parent == -1 || (tree[tree[v].parent].sons[0] != v && tree[tree[v].parent].sons[1] != v); } void splay(int v) { while (!is_root(v)) { int u = tree[v].parent; if (!is_root(u)) rotate((tree[tree[u].parent].sons[0] == u) == (tree[u].sons[0] == v) ? u : v); rotate(v); } push(v); } void expose(int v) { for (int u = v, prev = -1; u != -1; prev = u, u = tree[u].parent) { splay(u); tree[u].sons[1] = prev; relax(u); } splay(v); assert(tree[v].sons[1] == -1 && tree[v].parent == -1); } link_cut(int n = 0) : tree(n) {} int add() { tree.push_back(node()); return int(tree.size()) - 1; } void set_root(int root) { expose(root); tree[root].inv ^= 1; } bool connected(int v, int u) { if (v == u) return true; expose(v), expose(u); return tree[v].parent != -1; } bool link(int v, int u) { if (connected(v, u)) return false; tree[u].inv ^= 1; tree[u].parent = v; expose(u); return true; } bool cut(int v, int u) { if (v == u) return false; set_root(v), expose(u); if (tree[u].sons[0] != v) return false; tree[u].sons[0] = -1; relax(u); tree[v].parent = -1; return true; } int parent(int v, int root) { if (!connected(v, root)) return -1; set_root(root), expose(v); if (tree[v].sons[0] == -1) return -1; v = tree[v].sons[0]; while (push(v), tree[v].sons[1] != -1) v = tree[v].sons[1]; splay(v); return v; } int distance(int v, int u) { if (!connected(v, u)) return -1; set_root(v), expose(u); return tree[u].sons[0] == -1 ? 0 : tree[tree[u].sons[0]].size; } void update(int v, int value) { splay(v); tree[v].value = value; relax(v); } int query(int v, int u) { assert(v != u); set_root(v), expose(u); assert(tree[u].sons[0] != -1); return tree[u].value ^ tree[tree[u].sons[0]].tot; } }; int main() { using namespace std; ios::sync_with_stdio(false), cin.tie(nullptr); int n, m; cin >> n >> m; disjoin_set_union dsu(n); link_cut g(n + m); for (int id = n; id < n + m; id++) { int v, u, c; cin >> v >> u >> c; v--, u--; if (dsu.root(v) != dsu.root(u)) { cout << "YES\n"; dsu.unite(v, u); g.link(v, id); g.link(u, id); g.update(id, c); } else { if (!g.connected(v, u) || (g.query(v, u) ^ c) == 0) { cout << "NO\n"; continue; } cout << "YES\n"; while (u != v) { int w = g.parent(u, v); g.cut(u, w); u = w; } } } }
<image> William has two numbers a and b initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer k is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a new positive integer k) 1. add number k to both a and b, or 2. add number k to a and subtract k from b, or 3. add number k to b and subtract k from a. Note that after performing operations, numbers a and b may become negative as well. William wants to find out the minimal number of operations he would have to perform to make a equal to his favorite number c and b equal to his second favorite number d. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The only line of each test case contains two integers c and d (0 ≀ c, d ≀ 10^9), which are William's favorite numbers and which he wants a and b to be transformed into. Output For each test case output a single number, which is the minimal number of operations which William would have to perform to make a equal to c and b equal to d, or -1 if it is impossible to achieve this using the described operations. Example Input 6 1 2 3 5 5 3 6 6 8 0 0 0 Output -1 2 2 1 2 0 Note Let us demonstrate one of the suboptimal ways of getting a pair (3, 5): * Using an operation of the first type with k=1, the current pair would be equal to (1, 1). * Using an operation of the third type with k=8, the current pair would be equal to (-7, 9). * Using an operation of the second type with k=7, the current pair would be equal to (0, 2). * Using an operation of the first type with k=3, the current pair would be equal to (3, 5).
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastScanner in = new FastScanner(); int tt = in.nextInt(); for(int pp = 0; pp < tt; pp++) { int a = in.nextInt(); int b = in.nextInt(); if(Math.abs(a - b) % 2 == 0){ if(a - b == 0){ if(a == 0){ System.out.println(0); } else{ System.out.println(1); } } else{ System.out.println(2); } } else{ System.out.println(-1); } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
<image> William has an array of n integers a_1, a_2, ..., a_n. In one move he can swap two neighboring items. Two items a_i and a_j are considered neighboring if the condition |i - j| = 1 is satisfied. William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 10^5) which is the total number of items in William's array. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) which are William's array. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case output the minimal number of operations needed or -1 if it is impossible to get the array to a state when no neighboring numbers have the same parity. Example Input 5 3 6 6 1 1 9 6 1 1 1 2 2 2 2 8 6 6 6 2 3 4 5 1 Output 1 0 3 -1 2 Note In the first test case the following sequence of operations would satisfy the requirements: 1. swap(2, 3). Array after performing the operation: [6, 1, 6] In the second test case the array initially does not contain two neighboring items of the same parity. In the third test case the following sequence of operations would satisfy the requirements: 1. swap(3, 4). Array after performing the operation: [1, 1, 2, 1, 2, 2] 2. swap(2, 3). Array after performing the operation: [1, 2, 1, 1, 2, 2] 3. swap(4, 5). Array after performing the operation: [1, 2, 1, 2, 1, 2] In the fourth test case it is impossible to satisfy the requirements. In the fifth test case the following sequence of operations would satisfy the requirements: 1. swap(2, 3). Array after performing the operation: [6, 3, 2, 4, 5, 1] 2. swap(4, 5). Array after performing the operation: [6, 3, 2, 5, 4, 1]
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } template <class T> class Fenwick { private: public: vector<T> sum; int siz; Fenwick() {} Fenwick(int _siz) { siz = _siz; sum.resize(_siz); } void update(int x, T d) { for (int i = x; i < siz; i = i | (i + 1)) sum[i] += d; } T query(int x) { T ret = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) ret += sum[i]; return ret; } int kth(T k) { T cnt = 0; int ret = -1; for (int i = log2(siz); ~i; --i) { ret += 1 << i; if (ret >= siz - 1 || cnt + sum[ret] >= k + 1) ret -= 1 << i; else cnt += sum[ret]; } return ret + 1; } }; int n, a[100010]; void solve() { n = read(); for (int i = 1; i <= n; ++i) a[i] = read(); long long ans = 1e18; do { queue<int> q0, q1; for (int i = 1; i <= n; ++i) { if (a[i] % 2 == 0) q0.push(i); else q1.push(i); } Fenwick<long long> bit(n + 1); for (int i = 1; i <= n; ++i) bit.update(i, 1); long long sum = 0; for (int i = 1; i <= n; ++i) { if (i % 2 == 0) { if (q0.empty()) { sum = 1e18; break; } int x = q0.front(); q0.pop(); int rk = bit.query(x); sum += rk - 1; bit.update(x, -1); } else { if (q1.empty()) { sum = 1e18; break; } int x = q1.front(); q1.pop(); int rk = bit.query(x); sum += rk - 1; bit.update(x, -1); } } ans = min(ans, sum); } while (0); do { queue<int> q0, q1; for (int i = 1; i <= n; ++i) { if (a[i] % 2 == 1) q0.push(i); else q1.push(i); } Fenwick<long long> bit(n + 1); for (int i = 1; i <= n; ++i) bit.update(i, 1); long long sum = 0; for (int i = 1; i <= n; ++i) { if (i % 2 == 0) { if (q0.empty()) { sum = 1e18; break; } int x = q0.front(); q0.pop(); int rk = bit.query(x); sum += rk - 1; bit.update(x, -1); } else { if (q1.empty()) { sum = 1e18; break; } int x = q1.front(); q1.pop(); int rk = bit.query(x); sum += rk - 1; bit.update(x, -1); } } ans = min(ans, sum); } while (0); if (ans == 1e18) ans = -1; cout << ans << "\n"; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
<image> William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers c_1, c_2, ..., c_n where c_i is the number of consecutive brackets "(" if i is an odd number or the number of consecutive brackets ")" if i is an even number. For example for a bracket sequence "((())()))" a corresponding sequence of numbers is [3, 2, 1, 3]. You need to find the total number of continuous subsequences (subsegments) [l, r] (l ≀ r) of the original bracket sequence, which are regular bracket sequences. A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. Input The first line contains a single integer n (1 ≀ n ≀ 1000), the size of the compressed sequence. The second line contains a sequence of integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9), the compressed sequence. Output Output a single integer β€” the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type. Examples Input 5 4 1 2 3 1 Output 5 Input 6 1 3 2 1 2 4 Output 6 Input 6 1 1 1 1 2 2 Output 7 Note In the first example a sequence (((()(()))( is described. This bracket sequence contains 5 subsegments which form regular bracket sequences: 1. Subsequence from the 3rd to 10th character: (()(())) 2. Subsequence from the 4th to 5th character: () 3. Subsequence from the 4th to 9th character: ()(()) 4. Subsequence from the 6th to 9th character: (()) 5. Subsequence from the 7th to 8th character: () In the second example a sequence ()))(()(()))) is described. In the third example a sequence ()()(()) is described.
#include <bits/stdc++.h> using namespace std; signed main() { setlocale(LC_ALL, "rus"); std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<long long> dp(n); stack<pair<int, int>> st; long long ans = 0; for (int i = 0; i < n; ++i) { if (i & 1) { while (!st.empty() && st.top().first < a[i]) { ans += st.top().first; if (st.top().second > 0) { ans += dp[st.top().second - 1]; } a[i] -= st.top().first; st.pop(); } if (!st.empty()) { ans += a[i]; dp[i] = 1; if (a[i] == st.top().first) { if (st.top().second > 0) { ans += dp[st.top().second - 1]; dp[i] += dp[st.top().second - 1]; } st.pop(); } else { st.top().first -= a[i]; } a[i] = 0; } } else { st.emplace(a[i], i); } } cout << ans; }
<image> This is an interactive task William has a certain sequence of integers a_1, a_2, ..., a_n in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than 2 β‹… n of the following questions: * What is the result of a [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of two items with indices i and j (i β‰  j) * What is the result of a [bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) of two items with indices i and j (i β‰  j) You can ask William these questions and you need to find the k-th smallest number of the sequence. Formally the k-th smallest number is equal to the number at the k-th place in a 1-indexed array sorted in non-decreasing order. For example in array [5, 3, 3, 10, 1] 4th smallest number is equal to 5, and 2nd and 3rd are 3. Input It is guaranteed that for each element in a sequence the condition 0 ≀ a_i ≀ 10^9 is satisfied. Interaction In the first line you will be given two integers n and k (3 ≀ n ≀ 10^4, 1 ≀ k ≀ n), which are the number of items in the sequence a and the number k. After that, you can ask no more than 2 β‹… n questions (not including the "finish" operation). Each line of your output may be of one of the following types: * "or i j" (1 ≀ i, j ≀ n, i β‰  j), where i and j are indices of items for which you want to calculate the bitwise OR. * "and i j" (1 ≀ i, j ≀ n, i β‰  j), where i and j are indices of items for which you want to calculate the bitwise AND. * "finish res", where res is the kth smallest number in the sequence. After outputting this line the program execution must conclude. In response to the first two types of queries, you will get an integer x, the result of the operation for the numbers you have selected. After outputting a line do not forget to output a new line character and flush the output buffer. Otherwise you will get the "Idleness limit exceeded". To flush the buffer use: * fflush(stdout) in C++ * System.out.flush() in Java * stdout.flush() in Python * flush(output) in Pascal * for other languages refer to documentation If you perform an incorrect query the response will be -1. After receiving response -1 you must immediately halt your program in order to receive an "Incorrect answer" verdict. Hacking To perform a hack you will need to use the following format: The first line must contain two integers n and k (3 ≀ n ≀ 10^4, 1 ≀ k ≀ n), which are the number of items in the sequence a and the number k. The second line must contain n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9), the sequence a. Example Input 7 6 2 7 Output and 2 5 or 5 6 finish 5 Note In the example, the hidden sequence is [1, 6, 4, 2, 3, 5, 4]. Below is the interaction in the example. Query (contestant's program)| Response (interactor)| Notes ---|---|--- and 2 5| 2| a_2=6, a_5=3. Interactor returns bitwise AND of the given numbers. or 5 6| 7| a_5=3, a_6=5. Interactor returns bitwise OR of the given numbers. finish 5| | 5 is the correct answer. Note that you must find the value and not the index of the kth smallest number.
#include <bits/stdc++.h> using namespace std; const int N = 1e4 + 10; int a[N]; void solve() { int n, k; cin >> n >> k; int a1, a2, a3, o1, o2, o3; cout << "and 1 2\n"; cout.flush(); cin >> a1; cout << "and 1 3\n"; cout.flush(); cin >> a2; cout << "and 2 3\n"; cout.flush(); cin >> a3; cout << "or 1 2\n"; cout.flush(); cin >> o1; cout << "or 1 3\n"; cout.flush(); cin >> o2; cout << "or 2 3\n"; cout.flush(); cin >> o3; for (int i = 30; i >= 0; i--) { bool b = false; if ((1 << i) & a1) a[1] += (1 << i), a[2] += (1 << i), b = true; if ((1 << i) & a2) a[1] += (1 << i), a[3] += (1 << i), b = true; if ((1 << i) & a3) a[2] += (1 << i), a[3] += (1 << i), b = true; if (((1 << i) & a1) && ((1 << i) & a2)) a[1] -= (1 << i); if (((1 << i) & a1) && ((1 << i) & a3)) a[2] -= (1 << i); if (((1 << i) & a2) && ((1 << i) & a3)) a[3] -= (1 << i); if (b) continue; if ((1 << i) & o1 && (1 << i) & o2) a[1] += (1 << i); if ((1 << i) & o2 && (1 << i) & o3) a[3] += (1 << i); if ((1 << i) & o1 && (1 << i) & o3) a[2] += (1 << i); } for (int i = 4; i <= n; i++) { int curr1, curr2; cout << "or 1 " << i << "\n"; cout.flush(); cin >> curr1; cout << "and 1 " << i << "\n"; cout.flush(); cin >> curr2; for (int j = 30; j >= 0; j--) { if ((1 << j) & curr2) a[i] += (1 << j); else if (((1 << j) & curr1) && !(a[1] & (1 << j))) a[i] += (1 << j); } } sort(a + 1, a + 1 + n); cout << "finish " << a[k] << "\n"; cout.flush(); } int main() { solve(); }
<image> William has two arrays a and b, each consisting of n items. For some segments l..r of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each i from l to r holds a_i = b_i. To perform a balancing operation an even number of indices must be selected, such that l ≀ pos_1 < pos_2 < ... < pos_k ≀ r. Next the items of array a at positions pos_1, pos_3, pos_5, ... get incremented by one and the items of array b at positions pos_2, pos_4, pos_6, ... get incremented by one. William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently. Input The first line contains a two integers n and q (2 ≀ n ≀ 10^5, 1 ≀ q ≀ 10^5), the size of arrays a and b and the number of segments. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9). The third line contains n integers b_1, b_2, ..., b_n (0 ≀ b_i ≀ 10^9). Each of the next q lines contains two integers l_i and r_i (1 ≀ l_i < r_i ≀ n), the edges of segments. Output For each segment output a single number β€” the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays. Example Input 8 5 0 1 2 9 3 2 7 5 2 2 1 9 4 1 5 8 2 6 1 7 2 4 7 8 5 8 Output 1 3 1 -1 -1 Note For the first segment from 2 to 6 you can do one operation with pos = [2, 3, 5, 6], after this operation the arrays will be: a = [0, 2, 2, 9, 4, 2, 7, 5], b = [2, 2, 2, 9, 4, 2, 5, 8]. Arrays are equal on a segment from 2 to 6 after this operation. For the second segment from 1 to 7 you can do three following operations: 1. pos = [1, 3, 5, 6] 2. pos = [1, 7] 3. pos = [2, 7] After these operations, the arrays will be: a = [2, 2, 2, 9, 4, 2, 7, 5], b = [2, 2, 2, 9, 4, 2, 7, 8]. Arrays are equal on a segment from 1 to 7 after these operations. For the third segment from 2 to 4 you can do one operation with pos = [2, 3], after the operation arrays will be: a = [0, 2, 2, 9, 3, 2, 7, 5], b = [2, 2, 2, 9, 4, 1, 5, 8]. Arrays are equal on a segment from 2 to 4 after this operation. It is impossible to equalize the fourth and the fifth segment.
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1556E { public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int Q = infile.nextInt(); int[] arr = infile.nextInts(N); int[] brr = infile.nextInts(N); for(int i=0; i < N; i++) arr[i] -= brr[i]; //increase 1, decrease 1, etc long[] psums = new long[N]; psums[0] = arr[0]; for(int i=1; i < N; i++) psums[i] = psums[i-1]+arr[i]; LazySegTree segtree = new LazySegTree(N); LazySegTreeMin rmq = new LazySegTreeMin(N); for(int i=0; i < N; i++) { segtree.update(i, i, psums[i]); rmq.update(i, i, psums[i]); } ArrayList<Query> queries = new ArrayList<Query>(); for(int i=0; i < Q; i++) { int left = infile.nextInt()-1; int right = infile.nextInt()-1; queries.add(new Query(left, right, i)); } Collections.sort(queries); long[] res = new long[Q]; int pointer = 0; for(Query q: queries) { int L = q.left; int R = q.right; while(pointer < L) { segtree.update(pointer, N-1, -1*arr[pointer]); rmq.update(pointer, N-1, -1*arr[pointer]); pointer++; } long tot = psums[R]; if(L > 0) tot -= psums[L-1]; if(tot != 0) res[q.id] = -1; else { if(segtree.query(L, R) > 0) res[q.id] = -1; else res[q.id] = -1*rmq.query(L, R); } } StringBuilder sb = new StringBuilder(); for(long x: res) sb.append(x+"\n"); System.out.print(sb); } } class LazySegTree { //definitions private long NULL = Long.MIN_VALUE/2; private long[] tree; private long[] lazy; private int length; public LazySegTree(int N) { length = N; int b; for(b=0; (1<<b) < length; b++); tree = new long[1<<(b+1)]; lazy = new long[1<<(b+1)]; } public long query(int left, int right) { //left and right are 0-indexed return get(1, 0, length-1, left, right); } private long get(int v, int currL, int currR, int L, int R) { if(L > R) return NULL; if(L <= currL && currR <= R) return tree[v]; propagate(v); int mid = (currL+currR)/2; return comb(get(v*2, currL, mid, L, Math.min(R, mid)), get(v*2+1, mid+1, currR, Math.max(L, mid+1), R)); } public void update(int left, int right, long delta) { add(1, 0, length-1, left, right, delta); } private void add(int v, int currL, int currR, int L, int R, long delta) { if(L > R) return; if(currL == L && currR == R) { //exact covering tree[v] += delta; lazy[v] += delta; return; } propagate(v); int mid = (currL+currR)/2; add(v*2, currL, mid, L, Math.min(R, mid), delta); add(v*2+1, mid+1, currR, Math.max(L, mid+1), R, delta); tree[v] = comb(tree[v*2], tree[v*2+1]); } private void propagate(int v) { //tree[v] already has lazy[v] if(lazy[v] == 0) return; tree[v*2] += lazy[v]; lazy[v*2] += lazy[v]; tree[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private long comb(long a, long b) { return max(a,b); } } class LazySegTreeMin { //definitions private long NULL = Long.MAX_VALUE/2; private long[] tree; private long[] lazy; private int length; public LazySegTreeMin(int N) { length = N; int b; for(b=0; (1<<b) < length; b++); tree = new long[1<<(b+1)]; lazy = new long[1<<(b+1)]; } public long query(int left, int right) { //left and right are 0-indexed return get(1, 0, length-1, left, right); } private long get(int v, int currL, int currR, int L, int R) { if(L > R) return NULL; if(L <= currL && currR <= R) return tree[v]; propagate(v); int mid = (currL+currR)/2; return comb(get(v*2, currL, mid, L, Math.min(R, mid)), get(v*2+1, mid+1, currR, Math.max(L, mid+1), R)); } public void update(int left, int right, long delta) { add(1, 0, length-1, left, right, delta); } private void add(int v, int currL, int currR, int L, int R, long delta) { if(L > R) return; if(currL == L && currR == R) { //exact covering tree[v] += delta; lazy[v] += delta; return; } propagate(v); int mid = (currL+currR)/2; add(v*2, currL, mid, L, Math.min(R, mid), delta); add(v*2+1, mid+1, currR, Math.max(L, mid+1), R, delta); tree[v] = comb(tree[v*2], tree[v*2+1]); } private void propagate(int v) { //tree[v] already has lazy[v] if(lazy[v] == 0) return; tree[v*2] += lazy[v]; lazy[v*2] += lazy[v]; tree[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private long comb(long a, long b) { return min(a,b); } } class Query implements Comparable<Query> { public int left; public int right; public int id; public Query(int a, int b, int i) { left = a; right = b; id = i; } public int compareTo(Query oth) { return left-oth.left; } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
<image> William is not only interested in trading but also in betting on sports matches. n teams participate in each match. Each team is characterized by strength a_i. Each two teams i < j play with each other exactly once. Team i wins with probability (a_i)/(a_i + a_j) and team j wins with probability (a_j)/(a_i + a_j). The team is called a winner if it directly or indirectly defeated all other teams. Team a defeated (directly or indirectly) team b if there is a sequence of teams c_1, c_2, ... c_k such that c_1 = a, c_k = b and team c_i defeated team c_{i + 1} for all i from 1 to k - 1. Note that it is possible that team a defeated team b and in the same time team b defeated team a. William wants you to find the expected value of the number of winners. Input The first line contains a single integer n (1 ≀ n ≀ 14), which is the total number of teams participating in a match. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^6) β€” the strengths of teams participating in a match. Output Output a single integer β€” the expected value of the number of winners of the tournament modulo 10^9 + 7. Formally, let M = 10^9+7. It can be demonstrated that the answer can be presented as a irreducible fraction p/q, where p and q are integers and q not ≑ 0 \pmod{M}. Output a single integer equal to p β‹… q^{-1} mod M. In other words, output an integer x such that 0 ≀ x < M and x β‹… q ≑ p \pmod{M}. Examples Input 2 1 2 Output 1 Input 5 1 5 2 11 14 Output 642377629 Note To better understand in which situation several winners are possible let's examine the second test: One possible result of the tournament is as follows (a β†’ b means that a defeated b): * 1 β†’ 2 * 2 β†’ 3 * 3 β†’ 1 * 1 β†’ 4 * 1 β†’ 5 * 2 β†’ 4 * 2 β†’ 5 * 3 β†’ 4 * 3 β†’ 5 * 4 β†’ 5 Or more clearly in the picture: <image> In this case every team from the set \{ 1, 2, 3 \} directly or indirectly defeated everyone. I.e.: * 1st defeated everyone because they can get to everyone else in the following way 1 β†’ 2, 1 β†’ 2 β†’ 3, 1 β†’ 4, 1 β†’ 5. * 2nd defeated everyone because they can get to everyone else in the following way 2 β†’ 3, 2 β†’ 3 β†’ 1, 2 β†’ 4, 2 β†’ 5. * 3rd defeated everyone because they can get to everyone else in the following way 3 β†’ 1, 3 β†’ 1 β†’ 2, 3 β†’ 4, 3 β†’ 5. Therefore the total number of winners is 3.
#include <bits/stdc++.h> using namespace std; template <typename T> T inverse(T a, T m) { T u = 0, v = 1; while (a != 0) { T t = m / a; m -= t * a; swap(a, m); u -= t * v; swap(u, v); } assert(m == 1); return u; } template <typename T> class Modular { public: using Type = typename decay<decltype(T::value)>::type; constexpr Modular() : value() {} template <typename U> Modular(const U& x) { value = normalize(x); } template <typename U> static Type normalize(const U& x) { Type v; if (-mod() <= x && x < mod()) v = static_cast<Type>(x); else v = static_cast<Type>(x % mod()); if (v < 0) v += mod(); return v; } const Type& operator()() const { return value; } template <typename U> explicit operator U() const { return static_cast<U>(value); } constexpr static Type mod() { return T::value; } 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; } template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); } template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); } Modular& operator++() { return *this += 1; } Modular& operator--() { return *this -= 1; } Modular operator++(int) { Modular result(*this); *this += 1; return result; } Modular operator--(int) { Modular result(*this); *this -= 1; return result; } Modular operator-() const { return Modular(-value); } template <typename U = T> typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) { value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value)); return *this; } template <typename U = T> typename enable_if<is_same<typename Modular<U>::Type, long long>::value, Modular>::type& operator*=(const Modular& rhs) { long long q = static_cast<long long>(static_cast<long double>(value) * rhs.value / mod()); value = normalize(value * rhs.value - q * mod()); return *this; } template <typename U = T> typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) { value = normalize(value * rhs.value); return *this; } Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); } friend const Type& abs(const Modular& x) { return x.value; } template <typename U> friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs); template <typename U> friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs); template <typename V, typename U> friend V& operator>>(V& stream, Modular<U>& number); private: Type value; }; template <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; } template <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); } template <typename T, typename U> bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; } template <typename T> bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); } template <typename T, typename U> bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); } template <typename T, typename U> bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); } template <typename T> bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; } template <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; } template <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; } template <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; } template <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; } template <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; } template <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; } template <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; } template <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; } template <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; } template <typename T> Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; } template <typename T, typename U> Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; } template <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; } template <typename T, typename U> Modular<T> power(const Modular<T>& a, const U& b) { assert(b >= 0); Modular<T> x = a, res = 1; U p = b; while (p > 0) { if (p & 1) res *= x; x *= x; p >>= 1; } return res; } template <typename T> bool IsZero(const Modular<T>& number) { return number() == 0; } template <typename T> string to_string(const Modular<T>& number) { return to_string(number()); } template <typename U, typename T> U& operator<<(U& stream, const Modular<T>& number) { return stream << number(); } template <typename U, typename T> U& operator>>(U& stream, Modular<T>& number) { typename common_type<typename Modular<T>::Type, long long>::type x; stream >> x; number.value = Modular<T>::normalize(x); return stream; } constexpr int md = (int)1e9 + 7; using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<Mint> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } vector<vector<Mint>> p(n, vector<Mint>(n)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { p[i][j] = a[i] / (a[i] + a[j]); } } vector<Mint> s(1 << n); for (int t = 1; t < (1 << n); t++) { s[t] = 1; int u = (t - 1) & t; while (u > 0) { Mint cur = s[u]; for (int i = 0; i < n; i++) { if (u & (1 << i)) { for (int j = 0; j < n; j++) { if ((t ^ u) & (1 << j)) { cur *= p[i][j]; } } } } s[t] -= cur; u = (u - 1) & t; } } Mint ans = 0; for (int t = 1; t < (1 << n); t++) { Mint cur = s[t]; for (int i = 0; i < n; i++) { if (t & (1 << i)) { for (int j = 0; j < n; j++) { if (!(t & (1 << j))) { cur *= p[i][j]; } } } } ans += cur * __builtin_popcount(t); } cout << ans << '\n'; return 0; }
<image> As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from 0 to 2^n - 1. On each planet, there are gates that allow the player to move from planet i to planet j if the binary representations of i and j differ in exactly one bit. William wants to test you and see how you can handle processing the following queries in this game universe: * Destroy planets with numbers from l to r inclusively. These planets cannot be moved to anymore. * Figure out if it is possible to reach planet b from planet a using some number of planetary gates. It is guaranteed that the planets a and b are not destroyed. Input The first line contains two integers n, m (1 ≀ n ≀ 50, 1 ≀ m ≀ 5 β‹… 10^4), which are the number of bits in binary representation of each planets' designation and the number of queries, respectively. Each of the next m lines contains a query of two types: block l r β€” query for destruction of planets with numbers from l to r inclusively (0 ≀ l ≀ r < 2^n). It's guaranteed that no planet will be destroyed twice. ask a b β€” query for reachability between planets a and b (0 ≀ a, b < 2^n). It's guaranteed that planets a and b hasn't been destroyed yet. Output For each query of type ask you must output "1" in a new line, if it is possible to reach planet b from planet a and "0" otherwise (without quotation marks). Examples Input 3 3 ask 0 7 block 3 6 ask 0 7 Output 1 0 Input 6 10 block 12 26 ask 44 63 block 32 46 ask 1 54 block 27 30 ask 10 31 ask 11 31 ask 49 31 block 31 31 ask 2 51 Output 1 1 0 0 1 0 Note The first example test can be visualized in the following way: <image> Response to a query ask 0 7 is positive. Next after query block 3 6 the graph will look the following way (destroyed vertices are highlighted): <image> Response to a query ask 0 7 is negative, since any path from vertex 0 to vertex 7 must go through one of the destroyed vertices.
#include <bits/stdc++.h> using namespace std; inline int read_int() { int t = 0; bool sign = false; char c = getchar(); while (!isdigit(c)) { sign |= c == '-'; c = getchar(); } while (isdigit(c)) { t = (t << 1) + (t << 3) + (c & 15); c = getchar(); } return sign ? -t : t; } inline long long read_LL() { long long t = 0; bool sign = false; char c = getchar(); while (!isdigit(c)) { sign |= c == '-'; c = getchar(); } while (isdigit(c)) { t = (t << 1) + (t << 3) + (c & 15); c = getchar(); } return sign ? -t : t; } inline char get_char() { char c = getchar(); while (c == ' ' || c == '\n' || c == '\r') c = getchar(); return c; } inline void write(long long x) { register char c[21], len = 0; if (!x) return putchar('0'), void(); if (x < 0) x = -x, putchar('-'); while (x) c[++len] = x % 10, x /= 10; while (len) putchar(c[len--] + 48); } inline void space(long long x) { write(x), putchar(' '); } inline void enter(long long x) { write(x), putchar('\n'); } const int MAXL = 50, MAXM = 5e4 + 5; struct opt { long long a, b; int t; bool operator<(const opt &o) const { return a < o.a; } }; vector<opt> upd, nodes; void Insert(opt node, long long vl, long long vr) { if (node.a == node.b) nodes.push_back(node); else { long long vm = vl + vr >> 1; if (node.a <= vm && node.b > vm) { nodes.push_back(opt{node.a, vm, node.t}); nodes.push_back(opt{vm + 1, node.b, node.t}); } else if (node.b <= vm) Insert(node, vl, vm); else Insert(node, vm + 1, vr); } } vector<pair<int, int> > edges[MAXM]; void build(int ql, int qr, long long vl, long long vr) { if (ql == qr) return; long long vm = vl + vr >> 1, len = vm - vl + 1; int qm1 = ql, qm2; while (qm1 < qr && nodes[qm1 + 1].a <= vm) qm1++; qm2 = qm1 + (nodes[qm1].b > vm ? 0 : 1); int pos1 = ql, pos2 = qm2; while (pos1 <= qm1 && pos2 <= qr) { edges[min(nodes[pos1].t, nodes[pos2].t)].emplace_back(pos1, pos2); if (nodes[pos1].b + len < nodes[pos2].b) pos1++; else if (nodes[pos1].b + len > nodes[pos2].b) pos2++; else pos1++, pos2++; } build(ql, qm1, vl, vm); build(qm2, qr, vm + 1, vr); } int p[MAXM << 2]; int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); } pair<long long, long long> query[MAXM]; vector<long long> mp; char buf[MAXL]; int main() { int n = read_int(), m = read_int(); long long maxv = (1LL << n) - 1; for (int i = (0); i < (m); ++i) { scanf("%s", buf); long long l = read_LL(), r = read_LL(); if (buf[0] == 'b') { upd.push_back(opt{l, r, i}); query[i] = make_pair(-1LL, -1LL); } else query[i] = make_pair(l, r); } query[m] = make_pair(-1LL, -1LL); sort(upd.begin(), upd.end()); long long pos1 = 0; int pos2 = 0; while (pos1 <= maxv) { if (pos2 < upd.size()) { if (upd[pos2].a == pos1) { Insert(upd[pos2], 0, maxv); pos1 = upd[pos2++].b + 1; } else { Insert(opt{pos1, upd[pos2].a - 1, m}, 0, maxv); pos1 = upd[pos2].a; } } else { Insert(opt{pos1, maxv, m}, 0, maxv); pos1 = maxv + 1; } } build(0, nodes.size() - 1, 0, maxv); for (int i = (0); i < (nodes.size()); ++i) { p[i] = i; mp.push_back(nodes[i].b); } stack<int> ans; for (int i = m; i >= 0; i--) { for (pair<int, int> pr : edges[i]) { int x = Find(pr.first), y = Find(pr.second); if (x != y) p[x] = y; } if (query[i].first != -1) { int p1 = lower_bound(mp.begin(), mp.end(), query[i].first) - mp.begin(); int p2 = lower_bound(mp.begin(), mp.end(), query[i].second) - mp.begin(); p1 = Find(p1); p2 = Find(p2); if (p1 == p2) ans.push(1); else ans.push(0); } } while (!ans.empty()) { enter(ans.top()); ans.pop(); } return 0; }
<image> William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of n vertices. He wants to build a spanning tree of this graph, such that for the first k vertices the following condition is satisfied: the degree of a vertex with index i does not exceed d_i. Vertices from k + 1 to n may have any degree. William wants you to find the minimum weight of a spanning tree that satisfies all the conditions. A spanning tree is a subset of edges of a graph that forms a tree on all n vertices of the graph. The weight of a spanning tree is defined as the sum of weights of all the edges included in a spanning tree. Input The first line of input contains two integers n, k (2 ≀ n ≀ 50, 1 ≀ k ≀ min(n - 1, 5)). The second line contains k integers d_1, d_2, …, d_k (1 ≀ d_i ≀ n). The i-th of the next n - 1 lines contains n - i integers w_{i,i+1}, w_{i,i+2}, …, w_{i,n} (1 ≀ w_{i,j} ≀ 100): weights of edges (i,i+1),(i,i+2),…,(i,n). Output Print one integer: the minimum weight of a spanning tree under given degree constraints for the first k vertices. Example Input 10 5 5 3 4 2 1 29 49 33 12 55 15 32 62 37 61 26 15 58 15 22 8 58 37 16 9 39 20 14 58 10 15 40 3 19 55 53 13 37 44 52 23 59 58 4 69 80 29 89 28 48 Output 95
#include <bits/stdc++.h> using namespace std; int read() { int ret = 0; char c = getchar(); while (c > '9' || c < '0') c = getchar(); while (c >= '0' && c <= '9') ret = (ret << 3) + (ret << 1) + (c ^ 48), c = getchar(); return ret; } const int maxn = 55; const int maxk = 6; const int maxm = 2500; const int inf = 1e9; int n, k; int dlim[maxk]; struct edge { int from, to, val; } e1[15], e2[maxm]; int cnt1, cnt2; int ans; int d[maxk]; bool ini[maxm], x[maxm], y[maxm]; int dis[maxm], pre[maxm]; struct dsu { int fa[maxn]; void prework() { for (int i = 1; i <= n; i++) fa[i] = i; } int get(int x) { return x == fa[x] ? x : fa[x] = get(fa[x]); } void merge(int x, int y) { fa[get(x)] = get(y); } bool check(int x, int y) { return get(x) == get(y); } } S; queue<int> q; bool inq[maxm]; int ret = 0; bool deb = 0; struct graph { int head[maxm], ver[maxm * maxm], nxt[maxm * maxm], val[maxm * maxm], tot; void add(int x, int y, int z) { ver[++tot] = y; val[tot] = z; nxt[tot] = head[x]; head[x] = tot; } void clear() { tot = 0; for (int i = 1; i <= cnt2 + 2; i++) head[i] = 0; } int dis[maxm], pre[maxm], len[maxm]; bool inq[maxm]; void spfa() { for (int i = 1; i <= cnt2 + 2; i++) dis[i] = 0x3f3f3f3f, inq[i] = 0, pre[i] = 0; dis[cnt2 + 1] = 0; q.push(cnt2 + 1); inq[cnt2 + 1] = 1; while (!q.empty()) { int now = q.front(); q.pop(); inq[now] = 0; for (int i = head[now]; i; i = nxt[i]) if (dis[ver[i]] > dis[now] + val[i] || (dis[ver[i]] == dis[now] + val[i] && len[ver[i]] > len[now] + 1)) { dis[ver[i]] = dis[now] + val[i]; len[ver[i]] = len[now] + 1; pre[ver[i]] = now; if (!inq[ver[i]]) q.push(ver[i]); inq[ver[i]] = 1; } } } void update() { int now = cnt2 + 2; while (now) { ini[now] ^= 1; if (ini[now]) ret -= e2[now].val; else ret += e2[now].val; now = pre[now]; } } } o; bool calc(int chose) { for (int i = 1; i <= k; i++) d[i] = 0; S.prework(); for (int i = 1; i <= cnt1; i++) if ((chose >> (i - 1)) & 1) { d[e1[i].from]++, d[e1[i].to]++; S.merge(e1[i].from, e1[i].to); } for (int i = 1; i <= cnt2; i++) if (ini[i]) { if (e2[i].from <= k) d[e2[i].from]++; S.merge(e2[i].from, e2[i].to); } int s = cnt2 + 1, t = cnt2 + 2; o.clear(); for (int i = 1; i <= cnt2; i++) { if (ini[i]) x[i] = y[i] = 0; else { x[i] = (!S.check(e2[i].from, e2[i].to)); y[i] = (e2[i].from > k || d[e2[i].from] + 1 <= dlim[e2[i].from]); if (x[i]) o.add(s, i, e2[i].val); if (y[i]) o.add(i, t, 0); } } for (int i = 1; i <= cnt2; i++) { if (!ini[i]) continue; S.prework(); for (int j = 1; j <= cnt2; j++) if (ini[j] && j != i) S.merge(e2[j].from, e2[j].to); for (int i = 1; i <= cnt1; i++) if ((chose >> (i - 1)) & 1) S.merge(e1[i].from, e1[i].to); for (int j = 1; j <= cnt2; j++) { if (ini[j]) continue; if (!S.check(e2[j].from, e2[j].to)) o.add(i, j, e2[j].val); if (e2[j].from > k || d[e2[j].from] - (e2[j].from == e2[i].from) < dlim[e2[j].from]) o.add(j, i, -e2[i].val); } } o.spfa(); if (o.dis[t] == 0x3f3f3f3f) return false; o.update(); return true; } void solve(int chose) { for (int i = 1; i <= k; i++) d[i] = 0; S.prework(); ret = 0; for (int i = 1; i <= cnt1; i++) if ((chose >> (i - 1)) & 1) { d[e1[i].from]++; d[e1[i].to]++; ret += e1[i].val; if (d[e1[i].from] > dlim[e1[i].from]) return; if (d[e1[i].to] > dlim[e1[i].to]) return; if (S.check(e1[i].from, e1[i].to)) return; S.merge(e1[i].from, e1[i].to); } for (int i = 1; i <= cnt2; i++) ini[i] = 0; int cnt = 0; if (ret > ans) return; while (calc(chose)) { if (ret > ans) return; } ret = 0; bool flag = 1; S.prework(); for (int i = 1; i <= cnt1; i++) if ((chose >> (i - 1)) & 1) S.merge(e1[i].from, e1[i].to), ret += e1[i].val; for (int i = 1; i <= cnt2; i++) if (ini[i]) S.merge(e2[i].from, e2[i].to), ret += e2[i].val; for (int i = 1; i <= n; i++) if (!S.check(1, i)) return; ans = min(ret, ans); } int main() { n = read(); k = read(); for (int i = 1; i <= k; i++) dlim[i] = read(); for (int i = 1; i <= n - 1; i++) for (int j = 1; j <= n - i; j++) if (i <= k && i + j <= k) { cnt1++; e1[cnt1].from = i; e1[cnt1].to = i + j; e1[cnt1].val = read(); } else { cnt2++; e2[cnt2].from = i; e2[cnt2].to = i + j; e2[cnt2].val = read(); } ans = inf; for (int i = 0; i < (1 << cnt1); i++) solve(i); printf("%d\n", ans); return 0; }
Ezzat has an array of n integers (maybe negative). He wants to split it into two non-empty subsequences a and b, such that every element from the array belongs to exactly one subsequence, and the value of f(a) + f(b) is the maximum possible value, where f(x) is the average of the subsequence x. A sequence x is a subsequence of a sequence y if x can be obtained from y by deletion of several (possibly, zero or all) elements. The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence. For example, the average of [1,5,6] is (1+5+6)/3 = 12/3 = 4, so f([1,5,6]) = 4. Input The first line contains a single integer t (1 ≀ t ≀ 10^3)β€” the number of test cases. Each test case consists of two lines. The first line contains a single integer n (2 ≀ n ≀ 10^5). The second line contains n integers a_1, a_2, …, a_n (-10^9 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n over all test cases does not exceed 3β‹…10^5. Output For each test case, print a single value β€” the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≀ 10^{-6}. Example Input 4 3 3 1 2 3 -7 -6 -6 3 2 2 2 4 17 3 5 -3 Output 4.500000000 -12.500000000 4.000000000 18.666666667 Note In the first test case, the array is [3, 1, 2]. These are all the possible ways to split this array: * a = [3], b = [1,2], so the value of f(a) + f(b) = 3 + 1.5 = 4.5. * a = [3,1], b = [2], so the value of f(a) + f(b) = 2 + 2 = 4. * a = [3,2], b = [1], so the value of f(a) + f(b) = 2.5 + 1 = 3.5. Therefore, the maximum possible value 4.5. In the second test case, the array is [-7, -6, -6]. These are all the possible ways to split this array: * a = [-7], b = [-6,-6], so the value of f(a) + f(b) = (-7) + (-6) = -13. * a = [-7,-6], b = [-6], so the value of f(a) + f(b) = (-6.5) + (-6) = -12.5. Therefore, the maximum possible value -12.5.
def process(A): A = sorted(A) answer = -1*float('inf') S = sum(A) S1 = A[0] n1 = 1 answer = max(answer, S1/n1+(S-S1)/(n-n1)) for i in range(1, n-1): n1+=1 S1+=A[i] answer = max(answer, S1/n1+(S-S1)/(n-n1)) return answer t = int(input()) for i in range(t): n = int(input()) A = [int(x) for x in input().split()] print(process(A))
Moamen has an array of n distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once: 1. Split the array into exactly k non-empty subarrays such that each element belongs to exactly one subarray. 2. Reorder these subarrays arbitrary. 3. Merge the subarrays in their new order. A sequence a is a subarray of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above? Input The first line contains a single integer t (1 ≀ t ≀ 10^3) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains two integers n and k (1 ≀ k ≀ n ≀ 10^5). The second line contains n integers a_1, a_2, …, a_n (0 ≀ |a_i| ≀ 10^9). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of n over all test cases does not exceed 3β‹…10^5. Output For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower). Example Input 3 5 4 6 3 4 2 1 4 2 1 -4 0 -2 5 1 1 2 3 4 5 Output Yes No Yes Note In the first test case, a = [6, 3, 4, 2, 1], and k = 4, so we can do the operations as follows: 1. Split a into \{ [6], [3, 4], [2], [1] \}. 2. Reorder them: \{ [1], [2], [3,4], [6] \}. 3. Merge them: [1, 2, 3, 4, 6], so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only 2 subarrays. As an example, if we split it into \{ [1, -4], [0, -2] \}, we can reorder them into \{ [1, -4], [0, -2] \} or \{ [0, -2], [1, -4] \}. However, after merging the subarrays, it is impossible to get a sorted array.
for _ in range(int(input())): n,k=map(int, input().split()) li=list(map(int, input().split())) di={} a=1 for i in sorted(li): di[i]=a a+=1 changes=0 i=0 while i<n-1: while i<n-1 and di[li[i+1]]-di[li[i]]==1: i+=1 if i!=n-1: changes+=1 i+=1 if changes<k: print("Yes") else: print("No")
Moamen and Ezzat are playing a game. They create an array a of n non-negative integers where every element is less than 2^k. Moamen wins if a_1 \& a_2 \& a_3 \& … \& a_n β‰₯ a_1 βŠ• a_2 βŠ• a_3 βŠ• … βŠ• a_n. Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Please calculate the number of winning for Moamen arrays a. As the result may be very large, print the value modulo 1 000 000 007 (10^9 + 7). Input The first line contains a single integer t (1 ≀ t ≀ 5)β€” the number of test cases. Each test case consists of one line containing two integers n and k (1 ≀ n≀ 2β‹… 10^5, 0 ≀ k ≀ 2β‹… 10^5). Output For each test case, print a single value β€” the number of different arrays that Moamen wins with. Print the result modulo 1 000 000 007 (10^9 + 7). Example Input 3 3 1 2 1 4 0 Output 5 2 1 Note In the first example, n = 3, k = 1. As a result, all the possible arrays are [0,0,0], [0,0,1], [0,1,0], [1,0,0], [1,1,0], [0,1,1], [1,0,1], and [1,1,1]. Moamen wins in only 5 of them: [0,0,0], [1,1,0], [0,1,1], [1,0,1], and [1,1,1].
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, y = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') y = -1; ch = getchar(); } while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * y; } long long b[100005]; long long c[100005]; const int mod = 1e9 + 7; long long qpow(long long x, long long y) { long long res = 1, m = x; while (y) { if (y & 1) res = (res * m) % mod; m = (m * m) % mod; y >>= 1; } return res; } int main() { int T = read(); while (T--) { long long n = read(), k = read(); if (n & 1) { long long ans = qpow(2, n - 1); ans = (ans + 1) % mod; ans = qpow(ans, k); printf("%lld\n", ans); } else { long long ans = 1; long long m = 1; for (int i = 1; i <= k; i++) { ans = ((ans * (qpow(2, n - 1) - 1)) % mod + m) % mod; m = (m * qpow(2, n)) % mod; } ans = ((ans % mod) + mod) % mod; printf("%lld\n", ans); } } return 0; }
Moamen was drawing a grid of n rows and 10^9 columns containing only digits 0 and 1. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful. A grid is beautiful if and only if for every two consecutive rows there is at least one column containing 1 in these two rows. Ezzat will give you the number of rows n, and m segments of the grid that contain digits 1. Every segment is represented with three integers i, l, and r, where i represents the row number, and l and r represent the first and the last column of the segment in that row. For example, if n = 3, m = 6, and the segments are (1,1,1), (1,7,8), (2,7,7), (2,15,15), (3,1,1), (3,15,15), then the grid is: <image> Your task is to tell Ezzat the minimum number of rows that should be removed to make the grid beautiful. Input The first line contains two integers n and m (1 ≀ n, m ≀ 3β‹…10^5). Each of the next m lines contains three integers i, l, and r (1 ≀ i ≀ n, 1 ≀ l ≀ r ≀ 10^9). Each of these m lines means that row number i contains digits 1 in columns from l to r, inclusive. Note that the segments may overlap. Output In the first line, print a single integer k β€” the minimum number of rows that should be removed. In the second line print k distinct integers r_1, r_2, …, r_k, representing the rows that should be removed (1 ≀ r_i ≀ n), in any order. If there are multiple answers, print any. Examples Input 3 6 1 1 1 1 7 8 2 7 7 2 15 15 3 1 1 3 15 15 Output 0 Input 5 4 1 2 3 2 4 6 3 3 5 5 1 1 Output 3 2 4 5 Note In the first test case, the grid is the one explained in the problem statement. The grid has the following properties: 1. The 1-st row and the 2-nd row have a common 1 in the column 7. 2. The 2-nd row and the 3-rd row have a common 1 in the column 15. As a result, this grid is beautiful and we do not need to remove any row. In the second test case, the given grid is as follows: <image>
#include <bits/stdc++.h> using namespace std; struct segment_tree { int n; vector<pair<int, int>> st, lazy; segment_tree(int n) : n(n), st(2 * n, {0, -1}), lazy(2 * n) {} inline int id(int b, int e) { return (b + e - 1) | (b != e - 1); } void prop(int l, int r) { int cur = id(l, r); st[cur] = max(st[cur], lazy[cur]); if (l + 1 != r) { int mid = (l + r + 1) >> 1; lazy[id(l, mid)] = max(lazy[cur], lazy[id(l, mid)]); lazy[id(mid, r)] = max(lazy[id(l, mid)], lazy[cur]); } lazy[cur] = {0, -1}; } void upd(int li, int ri, pair<int, int> v) { upd(0, n, li, ri, v); } void upd(int l, int r, int li, int ri, pair<int, int> v) { if (li == ri) return; int cur = id(l, r); if (lazy[cur].first) prop(l, r); if (l >= ri || r <= li) return; if (li <= l && r <= ri) { lazy[cur] = v; prop(l, r); return; } int mid = (l + r + 1) >> 1; upd(l, mid, li, ri, v); upd(mid, r, li, ri, v); st[cur] = max(st[id(l, mid)], st[id(mid, r)]); } pair<int, int> que(int li, int ri) { return que(0, n, li, ri); } pair<int, int> que(int l, int r, int li, int ri) { int cur = id(l, r); if (lazy[cur].first) prop(l, r); if (l >= ri || r <= li) return {0, -1}; if (li <= l && r <= ri) return st[cur]; int mid = (l + r + 1) >> 1; return max(que(l, mid, li, ri), que(mid, r, li, ri)); } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; vector<int> w; vector<vector<pair<int, int>>> e(n); for (int i = 0; i < m; i++) { int t, l, r; cin >> t >> l >> r; e[t - 1].push_back({l, r + 1}); w.push_back(l); w.push_back(r + 1); } sort(w.begin(), w.end()); w.resize(unique(w.begin(), w.end()) - w.begin()); int sz = w.size(); map<int, int> mp; for (int i = 0; i < sz; i++) mp[w[i]] = i; for (int i = 0; i < n; i++) for (auto &j : e[i]) j.first = mp[j.first], j.second = mp[j.second]; segment_tree st(sz); vector<int> p(n, -1); for (int i = 0; i < n; i++) { pair<int, int> mx = {0, -1}; for (auto j : e[i]) { pair<int, int> t = st.que(j.first, j.second); mx = max(mx, t); } if (mx.first == 0) mx.second = -1; p[i] = mx.second; for (auto j : e[i]) st.upd(j.first, j.second, {mx.first + 1, i}); } int y = st.que(0, sz).second; vector<bool> in(n); while (y != -1) { in[y] = true; y = p[y]; } vector<int> ans; for (int i = 0; i < n; i++) if (!in[i]) ans.push_back(i); cout << ans.size() << "\n"; for (auto &i : ans) cout << i + 1 << " \n"[&i == &ans.back()]; return 0; }
This is an interactive problem. ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king. You compete on an 8Γ—8 chessboard, the rows are numerated from top to bottom, and the columns are numerated left to right, and the cell in row x and column y is denoted as (x, y). In one turn you can move the queen to any of the squares on the same horizontal line, vertical line, or any of the diagonals. For example, if the queen was on square (4, 5), you can move to (q_1, 5), (4, q_1), (q_1, 9-q_1), or (q_2, q_2+1) where (1 ≀ q_1 ≀ 8, q_1 β‰  4, 1 ≀ q_2 ≀ 7, q_2 β‰  4). Note that the queen cannot stay on its current cell. <image> In one turn, the king can move "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", or "Up-Right" such that he doesn't get out of the board. The king cannot move into a cell that is on the same row, column or diagonal with the queen (including the position of the queen itself). For example, if the king was on square (4, 5), he can move to (4+k_1, 5+k_2) where (-1 ≀ k_1,k_2 ≀ 1, (k_1, k_2) β‰  (0, 0)). <image> At the start of the game, you should place the queen at any location on the board, and this is done once per game. After that the king is secretly placed at any cell different from the queen's location. You do not know the position of the king. Then, the king and the queen take turns with the king moving first. The king moves to one of the possible directions ("Right", "Down", "Up-Left", etc.), and you are only given the direction it moves to. After that, you should move your queen by declaring the square to which your queen will move. The game follows like this until you win the game or run out of moves. You win if the king has no valid moves. You lose if after 130 moves of the queen the king still has valid moves. Input The first line contains a single integer t (1 ≀ t ≀ 60) β€” the number of test cases. Interaction In each test case, you should print the queen's starting cell immediately. If you placed the queen at the king's cell, you will win immediately. After that, you may make at most 130 moves. Each move is made in the format x y, where x and y are two integers (1 ≀ x,y ≀ 8) that denote the new row and column of the queen respectively. Your move should be a valid queen move. After the initial queen placement and after each move you will receive a string s that represents the direction of the king's move. It will be one of the following: "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", "Up-Right", or "Done" if you win the game. You should consider "Done" as the end of each test case. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If at any point you make an invalid query or try to make more than 130 queries for each test case, the game will terminate immediately and you will receive a Wrong Answer verdict. Example Input 1 Left Right Done Output 7 5 7 6 7 7 Note In the example, the hidden king was at (8, 8) at the start. The game follows like this: <image> <image>
#include <bits/stdc++.h> using namespace std; int T, row, col; string s; void mov(int x, int y) { printf("%d %d\n", x, y); col = y; cin >> s; } int scan(int row) { for (int c = (col == 1 ? 2 : 1); c <= 8; ++c) { mov(row, c); if (s == "Done") return true; if (s.find("Down") != -1) return false; if (s.find("Up") != -1) return scan(row); } return false; } int main() { scanf("%d", &T); while (T--) { col = 1; for (int row = 1; row <= 8; row++) { mov(row, col); if (col != 1) { if (s == "Done") break; col = 1; mov(row, col); } if (s == "Done") break; if (scan(row)) break; } } return 0; }
You have a permutation: an array a = [a_1, a_2, …, a_n] of distinct integers from 1 to n. The length of the permutation n is odd. You need to sort the permutation in increasing order. In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if a = [a_1, a_2, …, a_n], you can choose any odd integer p between 1 and n, inclusive, and set a to [a_p, a_{p-1}, …, a_1, a_{p+1}, a_{p+2}, …, a_n]. Find a way to sort a using no more than 5n/2 reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). Description of the test cases follows. The first line of each test case contains a single integer n (3 ≀ n ≀ 2021; n is odd) β€” the length of the permutation. The second line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the permutation itself. It is guaranteed that the sum of n over all test cases does not exceed 2021. Output For each test case, if it's impossible to sort the given permutation in at most 5n/2 reversals, print a single integer -1. Otherwise, print an integer m (0 ≀ m ≀ 5n/2), denoting the number of reversals in your sequence of steps, followed by m integers p_i (1 ≀ p_i ≀ n; p_i is odd), denoting the lengths of the prefixes of a to be reversed, in chronological order. Note that m doesn't have to be minimized. If there are multiple answers, print any. Example Input 3 3 1 2 3 5 3 4 5 2 1 3 2 1 3 Output 4 3 3 3 3 2 3 5 -1 Note In the first test case, the permutation is already sorted. Any even number of reversals of the length 3 prefix doesn't change that fact. In the second test case, after reversing the prefix of length 3 the permutation will change to [5, 4, 3, 2, 1], and then after reversing the prefix of length 5 the permutation will change to [1, 2, 3, 4, 5]. In the third test case, it's impossible to sort the permutation.
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T& x) { T t = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { t = (t << 3) + (t << 1) + ch - '0'; ch = getchar(); } x = f * t; } template <typename T, typename... Args> inline void read(T& t, Args&... args) { read(t); read(args...); } const int inf = 0x3f3f3f3f; const long long linf = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 3e3 + 9; const long long mod = 998244353; int n; int a[maxn], pos[maxn]; void re(vector<int>& v, int p) { v.push_back(p); reverse(a + 1, a + p + 1); for (int i = 1; i <= p; ++i) pos[a[i]] = i; } void solve() { read(n); vector<int> ans; bool f = 0; for (int i = 1; i <= n; ++i) { read(a[i]); pos[a[i]] = i; if (i % 2 != a[i] % 2) { f = 1; } } if (f) { cout << -1 << '\n'; return; } for (int i = n; i > 1; i -= 2) { int p1 = pos[i], p2 = pos[i - 1]; if (p1 != 1) re(ans, p1); p1 = 1, p2 = pos[i - 1]; if (p2 != 2) { re(ans, p2 - 1); } re(ans, i); p1 = pos[i], p2 = pos[i - 1]; re(ans, p1); re(ans, i); } cout << ans.size() << '\n'; for (auto i : ans) cout << i << ' '; cout << '\n'; } signed main() { int T = 1; read(T); while (T--) { solve(); } return 0; }
Consider the insertion sort algorithm used to sort an integer sequence [a_1, a_2, …, a_n] of length n in non-decreasing order. For each i in order from 2 to n, do the following. If a_i β‰₯ a_{i-1}, do nothing and move on to the next value of i. Otherwise, find the smallest j such that a_i < a_j, shift the elements on positions from j to i-1 by one position to the right, and write down the initial value of a_i to position j. In this case we'll say that we performed an insertion of an element from position i to position j. It can be noticed that after processing any i, the prefix of the sequence [a_1, a_2, …, a_i] is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence. For example, sorting [4, 5, 3, 1, 3] proceeds as follows: * i = 2: a_2 β‰₯ a_1, do nothing; * i = 3: j = 1, insert from position 3 to position 1: [3, 4, 5, 1, 3]; * i = 4: j = 1, insert from position 4 to position 1: [1, 3, 4, 5, 3]; * i = 5: j = 3, insert from position 5 to position 3: [1, 3, 3, 4, 5]. You are given an integer n and a list of m integer pairs (x_i, y_i). We are interested in sequences such that if you sort them using the above algorithm, exactly m insertions will be performed: first from position x_1 to position y_1, then from position x_2 to position y_2, ..., finally, from position x_m to position y_m. How many sequences of length n consisting of (not necessarily distinct) integers between 1 and n, inclusive, satisfy the above condition? Print this number modulo 998 244 353. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^5). Description of the test cases follows. The first line of each test case contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5; 0 ≀ m < n) β€” the length of the sequence and the number of insertions. The i-th of the following m lines contains two integers x_i and y_i (2 ≀ x_1 < x_2 < … < x_m ≀ n; 1 ≀ y_i < x_i). These lines describe the sequence of insertions in chronological order. It is guaranteed that the sum of m over all test cases does not exceed 2 β‹… 10^5. Note that there is no constraint on the sum of n of the same kind. Output For each test case, print the number of sequences of length n consisting of integers from 1 to n such that sorting them with the described algorithm produces the given sequence of insertions, modulo 998 244 353. Example Input 3 3 0 3 2 2 1 3 1 5 3 3 1 4 1 5 3 Output 10 1 21 Note In the first test case, the algorithm performs no insertions β€” therefore, the initial sequence is already sorted in non-decreasing order. There are 10 such sequences: [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]. In the second test case, the only sequence satisfying the conditions is [3, 2, 1]. In the third test case, [4, 5, 3, 1, 3] is one of the sought sequences.
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MOD = 998244353; const int MAXN = 4e5 + 1; int quick(int A, int B) { if (B == 0) return 1; int tmp = quick(A, B >> 1); tmp = 1ll * tmp * tmp % MOD; if (B & 1) tmp = 1ll * tmp * A % MOD; return tmp; } int inv(int A) { return quick(A, MOD - 2); } int fact[MAXN], ifact[MAXN]; int comb(int A, int B) { return 1ll * fact[A] * ifact[B] % MOD * ifact[A - B] % MOD; } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); vector<pair<int, int> > gt; struct Treap { int root = 0; struct node { pair<int, int> val; int ran, l, r, siz; }; vector<node> v; int new_node(pair<int, int> val) { if (v.empty()) { v.push_back(node{make_pair(0, -1), (int)rng() % INF, 0, 0, 0}); } v.push_back(node{val, (int)rng() % INF, 0, 0, val.second - val.first + 1}); return v.size() - 1; } void update(int index) { v[index].siz = v[index].val.second - v[index].val.first + 1; if (v[index].l) { v[index].siz += v[v[index].l].siz; } if (v[index].r) { v[index].siz += v[v[index].r].siz; } } void split_by_size(int base, int& x, int& y, int boundary) { if (!boundary) { x = 0; y = base; return; } if (!base) { x = y = 0; return; } if (v[v[base].l].siz + v[base].val.second - v[base].val.first + 1 < boundary) { x = base; split_by_size(v[base].r, v[x].r, y, boundary - v[v[base].l].siz - (v[base].val.second - v[base].val.first + 1)); update(x); } else { y = base; split_by_size(v[base].l, x, v[y].l, boundary); update(y); } } void getleft(int base, int& x, int& y) { if (!base) { x = y = 0; return; } if (!v[base].l) { x = base; y = v[base].r; v[base].r = 0; update(x); } else { y = base; getleft(v[base].l, x, v[y].l); update(y); } } int merge(int x, int y) { if (x == 0 || y == 0) return x + y; if (v[x].ran > v[y].ran) { v[x].r = merge(v[x].r, y); update(x); return x; } v[y].l = merge(x, v[y].l); update(y); return y; } void traval(int now) { if (now == 0) return; traval(v[now].l); gt.push_back(v[now].val); traval(v[now].r); } } fhq; int x[MAXN], y[MAXN]; void solve() { fhq.v.clear(); fhq.root = 0; int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { scanf("%d%d", &x[i], &y[i]); } vector<pair<pair<int, int>, int> > can; int pre = 0; for (int i = 1; i <= m; ++i) { if (pre + 1 <= x[i] - 1) { can.push_back(make_pair(make_pair(pre + 1, x[i] - 1), n)); } can.push_back(make_pair(make_pair(x[i], x[i]), y[i])); pre = x[i]; } for (auto it : can) { if (it.second == n) { fhq.root = fhq.merge(fhq.root, fhq.new_node(it.first)); } else { int x, y; fhq.split_by_size(fhq.root, x, y, it.second); int z; fhq.getleft(y, z, y); int nw = fhq.new_node(it.first); it.second -= fhq.v[x].siz; int _, __; _ = __ = 0; it.second--; pair<int, int> orz = fhq.v[z].val; if (it.second) { _ = fhq.new_node(make_pair(orz.first, orz.first + it.second - 1)); } if (it.second != fhq.v[z].siz) { __ = fhq.new_node(make_pair(orz.first + it.second, orz.second)); } fhq.root = fhq.merge(x, fhq.merge(fhq.merge(fhq.merge(_, nw), __), y)); } } gt.clear(); fhq.traval(fhq.root); int cnt = 0; for (int i = 0; i < gt.size(); ++i) { if (i) { if (gt[i - 1].second > gt[i].first) { cnt++; } } } int ans = comb(n - 1 + n - 1 - cnt + 1, n); printf("%d\n", ans); } int main() { fact[0] = 1; for (int i = 1; i <= 400000; ++i) fact[i] = 1ll * fact[i - 1] * i % MOD; for (int i = 0; i <= 400000; ++i) ifact[i] = inv(fact[i]); int t; scanf("%d", &t); while (t--) solve(); return 0; }
In a certain video game, the player controls a hero characterized by a single integer value: power. On the current level, the hero got into a system of n caves numbered from 1 to n, and m tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cave can be reached from any other cave by moving via tunnels. The hero starts the level in cave 1, and every other cave contains a monster. The hero can move between caves via tunnels. If the hero leaves a cave and enters a tunnel, he must finish his movement and arrive at the opposite end of the tunnel. The hero can use each tunnel to move in both directions. However, the hero can not use the same tunnel twice in a row. Formally, if the hero has just moved from cave i to cave j via a tunnel, he can not head back to cave i immediately after, but he can head to any other cave connected to cave j with a tunnel. It is known that at least two tunnels come out of every cave, thus, the hero will never find himself in a dead end even considering the above requirement. To pass the level, the hero must beat the monsters in all the caves. When the hero enters a cave for the first time, he will have to fight the monster in it. The hero can beat the monster in cave i if and only if the hero's power is strictly greater than a_i. In case of beating the monster, the hero's power increases by b_i. If the hero can't beat the monster he's fighting, the game ends and the player loses. After the hero beats the monster in cave i, all subsequent visits to cave i won't have any consequences: the cave won't have any monsters, and the hero's power won't change either. Find the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). Description of the test cases follows. The first line of each test case contains two integers n and m (3 ≀ n ≀ 1000; n ≀ m ≀ min((n(n-1))/(2), 2000)) β€” the number of caves and tunnels. The second line contains n-1 integers a_2, a_3, …, a_n (1 ≀ a_i ≀ 10^9) β€” values the hero's power are compared to while fighting monsters in caves 2, 3, …, n. The third line contains n-1 integers b_2, b_3, …, b_n (1 ≀ b_i ≀ 10^9) β€” increases applied to the hero's power for beating monsters in caves 2, 3, …, n. Each of the next m lines contains two integers u_i and v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i) β€” the numbers of caves connected with a tunnel. No two caves are connected with more than one tunnel. Any cave can be reached from any other cave by moving via tunnels. At least two tunnels come out of every cave. It is guaranteed that the sum of n over all test cases does not exceed 1000, and the sum of m over all test cases does not exceed 2000. Output For each test case print a single integer β€” the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level. Example Input 3 4 4 11 22 13 8 7 5 1 2 2 3 3 4 4 1 4 4 11 22 13 5 7 8 1 2 2 3 3 4 4 1 5 7 10 40 20 30 7 2 10 5 1 2 1 5 2 3 2 4 2 5 3 4 4 5 Output 15 15 19 Note In the first test case, the hero can pass the level with initial power 15 as follows: * move from cave 1 to cave 2: since 15 > 11, the hero beats the monster, and his power increases to 15 + 8 = 23; * move from cave 2 to cave 3: since 23 > 22, the hero beats the monster, and his power increases to 23 + 7 = 30; * move from cave 3 to cave 4: since 30 > 13, the hero beats the monster, and his power increases to 30 + 5 = 35. In the second test case, the situation is similar except that the power increases for beating monsters in caves 2 and 4 are exchanged. The hero can follow a different route, 1 β†’ 4 β†’ 3 β†’ 2, and pass the level with initial power 15. In the third test case, the hero can pass the level with initial power 19 as follows: * move from cave 1 to cave 2: since 19 > 10, the hero beats the monster, and his power increases to 19 + 7 = 26; * move from cave 2 to cave 4: since 26 > 20, the hero beats the monster, and his power increases to 26 + 10 = 36; * move from cave 4 to cave 5: since 36 > 30, the hero beats the monster, and his power increases to 36 + 5 = 41; * move from cave 5 to cave 2: there is no monster in this cave anymore, nothing happens; * move from cave 2 to cave 3: since 41 > 40, the hero beats the monster, and his power increases to 41 + 2 = 43.
#include <bits/stdc++.h> using namespace std; template <typename T> void chmin(T &x, const T &y) { if (x > y) x = y; } template <typename T> void chmax(T &x, const T &y) { if (x < y) x = y; } char readc() { char c; while (isspace((c = getchar()))) ; return c; } int read() { char c; while ((c = getchar()) < '-') ; if (c == '-') { int x = (c = getchar()) - '0'; while ((c = getchar()) >= '0') x = x * 10 + c - '0'; return -x; } int x = c - '0'; while ((c = getchar()) >= '0') x = x * 10 + c - '0'; return x; } const int N = 1000 + 5, INF = 1e9 + 10; int n, mx[N], fr[N], a[N], b[N], a0[N], b0[N], q[N]; vector<int> lk[N]; bool one(int p) { int t = 0; for (int i = 1; i <= n; ++i) { if (a[i] == INF) { for (auto j : lk[i]) { if (p > a[j]) { if (mx[j]) { a[j] = INF; return 1; } fr[j] = 0; mx[j] = min(INF, b[j] + p); q[++t] = j; } } } } for (int h = 1; h <= t; ++h) { int x = q[h]; for (auto y : lk[x]) if (y != fr[x]) { int d = mx[x]; if (d > a[y]) { if (mx[y]) { for (int i = y; i; i = fr[i]) a[i] = INF; for (int i = x; i; i = fr[i]) a[i] = INF; return 1; } mx[y] = min(INF, d + b[y]); fr[y] = x; q[++t] = y; } else if (a[y] == INF && fr[x]) { for (int i = x; i; i = fr[i]) a[i] = INF; return 1; } } } return 0; } bool check(int p0) { for (int i = 2; i <= n; ++i) a[i] = a0[i]; for (int i = 2; i <= n; ++i) b[i] = b0[i]; a[1] = INF; b[1] = 0; while (1) { bool ok = 1; int p = p0; for (int i = 2; i <= n; ++i) { ok &= a[i] == INF; if (a[i] == INF) p = min(INF, p + b[i]); } if (ok) break; for (int i = 1; i <= n; ++i) { mx[i] = fr[i] = 0; } if (!one(p)) return 0; } return 1; } int main() { int tt; cin >> tt; while (tt--) { int m; cin >> n >> m; for (int i = 2; i <= n; ++i) scanf("%d", a0 + i); for (int i = 2; i <= n; ++i) scanf("%d", b0 + i); for (int i = 1; i <= n; ++i) lk[i].clear(); while (m--) { int u, v; scanf("%d%d", &u, &v); lk[u].push_back(v); lk[v].push_back(u); } int l = 0, r = 1e9 + 5; while (l + 1 != r) { int mid = (l + r) / 2; if (check(mid)) r = mid; else l = mid; } cout << r << endl; } }
Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation. This day, Mocha got a sequence a of length n. In each operation, she can select an arbitrary interval [l, r] and for all values i (0≀ i ≀ r-l), replace a_{l+i} with a_{l+i} \& a_{r-i} at the same time, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). This operation can be performed any number of times. For example, if n=5, the array is [a_1,a_2,a_3,a_4,a_5], and Mocha selects the interval [2,5], then the new array is [a_1,a_2 \& a_5, a_3 \& a_4, a_4 \& a_3, a_5 \& a_2]. Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer n (1 ≀ n ≀ 100) β€” the length of the sequence. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 10^9). Output For each test case, print one integer β€” the minimal value of the maximum value in the sequence. Example Input 4 2 1 2 3 1 1 3 4 3 11 3 7 5 11 7 15 3 7 Output 0 1 3 3 Note In the first test case, Mocha can choose the interval [1,2], then the sequence becomes [ 0, 0], where the first element is 1 \& 2, and the second element is 2 \& 1. In the second test case, Mocha can choose the interval [1,3], then the sequence becomes [ 1,1,1], where the first element is 1 \& 3, the second element is 1 \& 1, and the third element is 3 \& 1.
import sys import os from math import * from functools import reduce # sys.stdin = open(r"hack.txt", "r") def main(): t = int(input()) for i in range(t): n = int(input()) l = list(map(int, input().split())) print(reduce(lambda x, y: x & y, l)) if __name__ == "__main__": main()
As their story unravels, a timeless tale is told once again... Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow. There are n squares arranged in a row, and each of them can be painted either red or blue. Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square. Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color. For example, the imperfectness of "BRRRBBR" is 3, with "BB" occurred once and "RR" occurred twice. Your goal is to minimize the imperfectness and print out the colors of the squares after painting. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Each test case consists of two lines. The first line of each test case contains an integer n (1≀ n≀ 100) β€” the length of the squares row. The second line of each test case contains a string s with length n, containing characters 'B', 'R' and '?'. Here 'B' stands for a blue square, 'R' for a red square, and '?' for a blank square. Output For each test case, print a line with a string only containing 'B' and 'R', the colors of the squares after painting, which imperfectness is minimized. If there are multiple solutions, print any of them. Example Input 5 7 ?R???BR 7 ???R??? 1 ? 1 B 10 ?R??RB??B? Output BRRBRBR BRBRBRB B B BRRBRBBRBR Note In the first test case, if the squares are painted "BRRBRBR", the imperfectness is 1 (since squares 2 and 3 have the same color), which is the minimum possible imperfectness.
import java.io.*; public class MochaRedandBlue { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(reader.readLine()); while (t-- > 0) { int n = Integer.parseInt(reader.readLine()); String str = reader.readLine(); char[] arr = str.toCharArray(); int cnt = 0; for (int i = 0; i < n; i++) { if (arr[i] == '?') { cnt++; } } if (cnt == 0) { // nothing } else if (cnt == n) { for (int i = 0; i < n; i++) { if (i % 2 == 0) { arr[i] = 'B'; } else { arr[i] = 'R'; } } } else { int idx = 0; int flag = 0; int i = 0; while (i < n - 1) { if (arr[idx] == '?' && flag == 0) { idx++; i++; } else { flag = 1; if (arr[i] == 'R' && arr[i + 1] == '?') { arr[i + 1] = 'B'; } else if (arr[i] == 'B' && arr[i + 1] == '?') { arr[i + 1] = 'R'; } i++; } } if (arr[i - 1] == 'R' && arr[i] == '?') { arr[i] = 'B'; } else if (arr[i - 1] == 'B' && arr[i] == '?') { arr[i] = 'R'; } while (idx > 0) { if (arr[idx] == 'R') { arr[idx - 1] = 'B'; } else { arr[idx - 1] = 'R'; } idx--; } } String ans = ""; for (char c : arr) { ans += c; } writer.write(ans + "\n"); writer.flush(); } } }
The city where Mocha lives in is called Zhijiang. There are n+1 villages and 2n-1 directed roads in this city. There are two kinds of roads: * n-1 roads are from village i to village i+1, for all 1≀ i ≀ n-1. * n roads can be described by a sequence a_1,…,a_n. If a_i=0, the i-th of these roads goes from village i to village n+1, otherwise it goes from village n+1 to village i, for all 1≀ i≀ n. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer n (1 ≀ n ≀ 10^4) β€” indicates that the number of villages is n+1. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 1). If a_i=0, it means that there is a road from village i to village n+1. If a_i=1, it means that there is a road from village n+1 to village i. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For each test case, print a line with n+1 integers, where the i-th number is the i-th village they will go through. If the answer doesn't exist, print -1. If there are multiple correct answers, you can print any one of them. Example Input 2 3 0 1 0 3 1 1 0 Output 1 4 2 3 4 1 2 3 Note In the first test case, the city looks like the following graph: <image> So all possible answers are (1 β†’ 4 β†’ 2 β†’ 3), (1 β†’ 2 β†’ 3 β†’ 4). In the second test case, the city looks like the following graph: <image> So all possible answers are (4 β†’ 1 β†’ 2 β†’ 3), (1 β†’ 2 β†’ 3 β†’ 4), (3 β†’ 4 β†’ 1 β†’ 2), (2 β†’ 3 β†’ 4 β†’ 1).
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; const int INF = 0x3f3f3f3f; const long long INFF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; int t, n, a[N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; if (a[n] == 0) { for (int i = 1; i <= n; i++) cout << i << ' '; cout << n + 1 << '\n'; return; } int x = -1; for (int i = 0; i < n; i++) { if (a[i] == 0 && a[i + 1] == 1) x = i; } if (x == -1) cout << -1 << '\n'; else { for (int i = 1; i <= x; i++) cout << i << ' '; cout << n + 1 << ' '; x++; for (int i = x; i <= n; i++) cout << i << ' '; cout << '\n'; } } int main() { cin >> t; while (t--) { solve(); } return 0; }
This is the easy version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved. A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 1 to n, and they would like to add edges to their forests such that: * After adding edges, both of their graphs are still forests. * They add the same edges. That is, if an edge (u, v) is added to Mocha's forest, then an edge (u, v) is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add. Input The first line contains three integers n, m_1 and m_2 (1 ≀ n ≀ 1000, 0 ≀ m_1, m_2 < n) β€” the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next m_1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edges in Mocha's forest. Each of the next m_2 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edges in Diana's forest. Output The first line contains only one integer h, the maximum number of edges Mocha and Diana can add (in each forest). Each of the next h lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edge you add each time. If there are multiple correct answers, you can print any one of them. Examples Input 3 2 2 1 2 2 3 1 2 1 3 Output 0 Input 5 3 2 5 4 2 1 4 3 4 3 1 4 Output 1 2 4 Input 8 1 2 1 7 2 6 1 5 Output 5 5 2 2 3 3 4 4 7 6 8 Note In the first example, we cannot add any edge. In the second example, the initial forests are as follows. <image> We can add an edge (2, 4). <image>
#include <bits/stdc++.h> using namespace std; const int maxn = 1000; vector<int> dis1(maxn), dis2(maxn); void init() { for (int i = 0; i < maxn; i++) { dis1[i] = dis2[i] = i; } } int find_root(int w, int n) { if (w == 1) return dis1[n] == n ? n : dis1[n] = find_root(w, dis1[n]); else if (w == 2) return dis2[n] == n ? n : dis2[n] = find_root(w, dis2[n]); } void connect_dis(int w, int a, int b) { if (w == 1) dis1[find_root(w, a)] = find_root(w, b); else if (w == 2) dis2[find_root(w, a)] = find_root(w, b); } int main() { init(); int n, m1, m2, a, b, num = 0; vector<pair<int, int>> ans; cin >> n >> m1 >> m2; for (int i = 0; i < m1; i++) { cin >> a >> b; connect_dis(1, a - 1, b - 1); } for (int i = 0; i < m2; i++) { cin >> a >> b; connect_dis(2, a - 1, b - 1); } for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if ((find_root(1, i) != find_root(1, j)) && (find_root(2, i) != find_root(2, j))) { num++; ans.push_back({i + 1, j + 1}); connect_dis(1, i, j); connect_dis(2, i, j); } } } cout << num << '\n'; for (auto i : ans) cout << i.first << ' ' << i.second << '\n'; }
This is the hard version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved. A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 1 to n, and they would like to add edges to their forests such that: * After adding edges, both of their graphs are still forests. * They add the same edges. That is, if an edge (u, v) is added to Mocha's forest, then an edge (u, v) is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add. Input The first line contains three integers n, m_1 and m_2 (1 ≀ n ≀ 10^5, 0 ≀ m_1, m_2 < n) β€” the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next m_1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edges in Mocha's forest. Each of the next m_2 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edges in Diana's forest. Output The first line contains only one integer h, the maximum number of edges Mocha and Diana can add. Each of the next h lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the edge you add each time. If there are multiple correct answers, you can print any one of them. Examples Input 3 2 2 1 2 2 3 1 2 1 3 Output 0 Input 5 3 2 5 4 2 1 4 3 4 3 1 4 Output 1 2 4 Input 8 1 2 1 7 2 6 1 5 Output 5 5 2 2 3 3 4 4 7 6 8 Note In the first example, we cannot add any edge. In the second example, the initial forests are as follows. <image> We can add an edge (2, 4). <image>
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 7; int rd() { int s = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { s = s * 10 + c - '0'; c = getchar(); } return s * f; } int n, m1, m2, k, tot, fa[2][maxn]; vector<pair<int, int> > ans; int get(int x, int num) { return fa[num][x] == x ? x : fa[num][x] = get(fa[num][x], num); } int S[maxn], stop; int T[maxn], ttop; int main() { n = rd(); for (int i = 1; i <= n; i++) fa[0][i] = fa[1][i] = i; m1 = rd(), m2 = rd(); for (int i = 1, u, v; i <= m1; i++) { u = rd(); v = rd(); u = get(u, 0), v = get(v, 0); if (u > v) fa[0][u] = v; if (u < v) fa[0][v] = u; } for (int i = 1, u, v; i <= m2; i++) { u = rd(); v = rd(); u = get(u, 1), v = get(v, 1); if (u > v) fa[1][u] = v; if (u < v) fa[1][v] = u; } for (int i = 2; i <= n; i++) { int f0 = get(i, 0), f1 = get(i, 1); if (f0 != 1 && f1 != 1) { fa[0][f0] = 1; fa[1][f1] = 1; tot++; ans.push_back(make_pair(i, 1)); } } for (int i = 2, j = 2; i <= n; i++) { int f0 = get(i, 0); if (f0 != 1) { int f1 = get(j, 1); while (f1 == 1 && j <= n) { f1 = get(++j, 1); } if (j > n) break; fa[0][f0] = 1; fa[1][f1] = 1; tot++; ans.push_back(make_pair(i, j)); } } printf("%d\n", tot); for (int i = 0; i < tot; i++) { printf("%d %d\n", ans[i].first, ans[i].second); } }
Mocha wants to be an astrologer. There are n stars which can be seen in Zhijiang, and the brightness of the i-th star is a_i. Mocha considers that these n stars form a constellation, and she uses (a_1,a_2,…,a_n) to show its state. A state is called mathematical if all of the following three conditions are satisfied: * For all i (1≀ i≀ n), a_i is an integer in the range [l_i, r_i]. * βˆ‘ _{i=1} ^ n a_i ≀ m. * \gcd(a_1,a_2,…,a_n)=1. Here, \gcd(a_1,a_2,…,a_n) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a_1,a_2,…,a_n. Mocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo 998 244 353. Two states (a_1,a_2,…,a_n) and (b_1,b_2,…,b_n) are considered different if there exists i (1≀ i≀ n) such that a_i β‰  b_i. Input The first line contains two integers n and m (2 ≀ n ≀ 50, 1 ≀ m ≀ 10^5) β€” the number of stars and the upper bound of the sum of the brightness of stars. Each of the next n lines contains two integers l_i and r_i (1 ≀ l_i ≀ r_i ≀ m) β€” the range of the brightness of the i-th star. Output Print a single integer β€” the number of different mathematical states of this constellation, modulo 998 244 353. Examples Input 2 4 1 3 1 2 Output 4 Input 5 10 1 10 1 10 1 10 1 10 1 10 Output 251 Input 5 100 1 94 1 96 1 91 4 96 6 97 Output 47464146 Note In the first example, there are 4 different mathematical states of this constellation: * a_1=1, a_2=1. * a_1=1, a_2=2. * a_1=2, a_2=1. * a_1=3, a_2=1.
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5, mod = 998244353; long long f[55][N], l[N], r[N], sum[N], prim[N], nump, vis[N], mu[N]; void init() { mu[1] = 1; for (int i = 2; i < N; i++) { if (!vis[i]) { prim[++nump] = i; mu[i] = -1; } for (int j = 1; j <= nump && i * prim[j] < N; j++) { vis[i * prim[j]] = 1; if (i % prim[j] == 0) break; else mu[i * prim[j]] = -mu[i]; } } } int main() { long long n, m; scanf("%lld%lld", &n, &m); for (int i = 1; i <= n; i++) scanf("%lld%lld", l + i, r + i); long long ans = 0; init(); for (int d = 1; d <= m; d++) { f[0][0] = 1; long long cnt = 0; if (mu[d]) { for (int i = 1; i <= n; i++) { sum[0] = f[i - 1][0]; for (int j = 1; j <= m / d; j++) sum[j] = (sum[j - 1] + f[i - 1][j]) % mod; for (int j = (l[i] + d - 1) / d; j <= m / d; j++) { if (j >= r[i] / d) f[i][j] = sum[j - (l[i] + d - 1) / d] - sum[j - r[i] / d - 1]; else f[i][j] = sum[j - (l[i] + d - 1) / d]; f[i][j] = f[i][j] % mod; } } for (int j = 1; j <= m / d; j++) cnt = (cnt + f[n][j]) % mod; ans += mu[d] * cnt; ans = ans % mod; ans += mod; ans = ans % mod; } } cout << ans << endl; return 0; }
Polycarp doesn't like integers that are divisible by 3 or end with the digit 3 in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too. Polycarp starts to write out the positive (greater than 0) integers which he likes: 1, 2, 4, 5, 7, 8, 10, 11, 14, 16, .... Output the k-th element of this sequence (the elements are numbered from 1). Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing one integer k (1 ≀ k ≀ 1000). Output For each test case, output in a separate line one integer x β€” the k-th element of the sequence that was written out by Polycarp. Example Input 10 1 2 3 4 5 6 7 8 9 1000 Output 1 2 4 5 7 8 10 11 14 1666
#include <bits/stdc++.h> using namespace std; int main() { int n, t; cin >> t; while (t--) { int count = 0; int ans; cin >> n; for (int i = 1; i <= 1666; i++) { if ((i % 10 != 3) && i % 3 != 0) { count++; } if (count == n) { ans = i; break; } } cout << ans << endl; } return 0; }
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number 1. Each person is looking through the circle's center at the opposite person. <image> A sample of a circle of 6 persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number a is looking at the person with the number b (and vice versa, of course). What is the number associated with a person being looked at by the person with the number c? If, for the specified a, b, and c, no such circle exists, output -1. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing three distinct integers a, b, c (1 ≀ a,b,c ≀ 10^8). Output For each test case output in a separate line a single integer d β€” the number of the person being looked at by the person with the number c in a circle such that the person with the number a is looking at the person with the number b. If there are multiple solutions, print any of them. Output -1 if there's no circle meeting the given conditions. Example Input 7 6 2 4 2 3 1 2 4 10 5 3 4 1 3 2 2 5 4 4 3 2 Output 8 -1 -1 -1 4 1 -1 Note In the first test case, there's a desired circle of 8 people. The person with the number 6 will look at the person with the number 2 and the person with the number 8 will look at the person with the number 4. In the second test case, there's no circle meeting the conditions. If the person with the number 2 is looking at the person with the number 3, the circle consists of 2 people because these persons are neighbors. But, in this case, they must have the numbers 1 and 2, but it doesn't meet the problem's conditions. In the third test case, the only circle with the persons with the numbers 2 and 4 looking at each other consists of 4 people. Therefore, the person with the number 10 doesn't occur in the circle.
import math t = int(input()) for _ in range(t): a,b,c = map(int,input().split()) n = abs(b-a)*2 diff = abs(b-a) if a>n or b>n or c>n: print(-1) continue x1,x2 = c + diff , c-diff ans = -1 if 1<=x1<=n: ans = c+diff if 1<=x2<=n: ans = c-diff print(ans)
Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from 1, starting from the topmost one. The columns are numbered from 1, starting from the leftmost one. Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from 1 and so on to the table as follows. <image> The figure shows the placement of the numbers from 1 to 10. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number 1. Then he writes in the table all positive integers beginning from 2 sequentially using the following algorithm. First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above). After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on. A friend of Polycarp has a favorite number k. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number k. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing one integer k (1 ≀ k ≀ 10^9) which location must be found. Output For each test case, output in a separate line two integers r and c (r, c β‰₯ 1) separated by spaces β€” the indices of the row and the column containing the cell filled by the number k, respectively. Example Input 7 11 14 5 4 1 2 1000000000 Output 2 4 4 3 1 3 2 1 1 1 1 2 31623 14130
import java.util.*; import java.io.*; public class C_1560 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int k = sc.nextInt(); int start = 1, end = (int)(Math.sqrt(1e9) + 5); while(start < end) { int mid = (start + end) >> 1; if(mid * mid >= k) end = mid; else start = mid + 1; } k -= (start - 1) * (start - 1); if(k <= start) pw.println(k + " " + start); else pw.println(start + " " + (start - (k - start))); } pw.flush(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
You are given an integer n. In 1 move, you can do one of the following actions: * erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); * add one digit to the right. The actions may be performed in any order any number of times. Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number 301 the digit 3, the result is the number 01 (not 1). You need to perform the minimum number of actions to make the number any power of 2 (i.e. there's an integer k (k β‰₯ 0) such that the resulting number is equal to 2^k). The resulting number must not have leading zeroes. E.g. consider n=1052. The answer is equal to 2. First, let's add to the right one digit 4 (the result will be 10524). Then let's erase the digit 5, so the result will be 1024 which is a power of 2. E.g. consider n=8888. The answer is equal to 3. Let's erase any of the digits 8 three times. The result will be 8 which is a power of 2. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing one integer n (1 ≀ n ≀ 10^9). Output For each test case, output in a separate line one integer m β€” the minimum number of moves to transform the number into any power of 2. Example Input 12 1052 8888 6 75 128 1 301 12048 1504 6656 1000000000 687194767 Output 2 3 1 3 0 0 2 1 3 4 9 2 Note The answer for the first test case was considered above. The answer for the second test case was considered above. In the third test case, it's enough to add to the right the digit 4 β€” the number 6 will turn into 64. In the fourth test case, let's add to the right the digit 8 and then erase 7 and 5 β€” the taken number will turn into 8. The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move. In the seventh test case, you can delete first of all the digit 3 (the result is 01) and then the digit 0 (the result is 1).
import java.io.*; import java.util.*; public class Main { static int M = 1_000_000_007; static int INF = 2_000_000_000; static int N = (int)1e5+1; static final FastScanner fs = new FastScanner(); //variable public static void main(String[] args) throws IOException { int T = fs.nextInt(); ArrayList<String> pow = new ArrayList<>(); for(long i=1;i<=1e16;i*=2) { pow.add(Long.toString(i)); } while(T-- > 0) { String n = fs.next(); int ans = INF; for(String s : pow) { int count = matchCount(s.toCharArray(),n.toCharArray(),s.length(),n.length()); ans = Math.min(ans,s.length()+n.length()-2*count); } System.out.println(Math.min(ans,n.length()+1)); } } //class //function static int matchCount( char[] X, char[] Y, int m, int n ) { int ans = 0; int j = 0; for(int k=0;j<m && k<n;k++) { if(Y[k] == X[j]){ ans++; j++; } } return ans; } static void build(int a[],int seg[],int ind,int low,int high) { if(low == high) { seg[ind] = a[low]; return; } int mid = (low + high)/2; build(a, seg, 2*ind + 1, low, mid); build(a, seg, 2*ind + 2, mid + 1, high); seg[ind] = Math.max(seg[2*ind + 1], seg[2*ind + 2]); } static long query(int ind, int seg[], int l, int h, int low, int high) { if(low > h || high < l) return -INF; if(low >= l && high <= h) return seg[ind]; int mid = (low + high)/2; long left = query(2*ind + 1, seg, l, h, low, mid); long right = query(2*ind + 2, seg, l, h, mid + 1, high); return Math.max(left, right); } // Template static long factorial(int n) { long fact = 1; for(int i=1;i<=n;i++) { fact *= i; } return fact; } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } static void premutation(int n, ArrayList<Integer> arr,boolean[] chosen) { if(arr.size() == n) { System.out.println(arr); }else { for(int i=1; i<=n; i++) { if(chosen[i]) continue; arr.add(i); chosen[i] = true; premutation(n,arr,chosen); arr.remove(new Integer(i)); chosen[i] = false; } } } static boolean isPalindrome(char[] c) { int n = c.length; for(int i=0; i<n/2; i++) { if(c[i] != c[n-i-1]) return false; } return true; } static long nCk(int n, int k) { return (modMult(fact(n),fastexp(modMult(fact(n-k),fact(k)),M-2))); } static long fact (long n) { long fact =1; for(int i=1; i<=n; i++) { fact = modMult(fact,i); } return fact%M; } static int modMult(long a,long b) { return (int) (a*b%M); } static int negMult(long a,long b) { return (int)((a*b)%M + M)%M; } static long fastexp(long x, int y){ if(y==1) return x; if(y == 0) return 1; long ans = fastexp(x,y/2); if(y%2 == 0) return modMult(ans,ans); else return modMult(ans,modMult(ans,x)); } static final Random random = new Random(); static void ruffleSort(int[] arr) { int n = arr.length; for(int i=0; i<n; i++) { int j = random.nextInt(n); int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } public static class Pairs implements Comparable<Pairs> { int f,s; Pairs(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pairs p) { if(this.f != p.f) return Integer.compare(this.f,p.f); return -Integer.compare(this.s,p.s); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pairs)) return false; Pairs pairs = (Pairs) o; return f == pairs.f && s == pairs.s; } @Override public int hashCode() { return Objects.hash(f, s); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer str = new StringTokenizer(""); String next() throws IOException { while(!str.hasMoreTokens()) str = new StringTokenizer(br.readLine()); return str.nextToken(); } char nextChar() throws IOException { return next().charAt(0); } int nextInt() throws IOException { return Integer.parseInt(next()); } float nextFloat() throws IOException { return Float.parseFloat(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } byte nextByte() throws IOException { return Byte.parseByte(next()); } int [] arrayIn(int n) throws IOException { int[] arr = new int[n]; for(int i=0; i<n; i++) { arr[i] = nextInt(); } return arr; } }
Polycarp has a string s. Polycarp performs the following actions until the string s is empty (t is initially an empty string): * he adds to the right to the string t the string s, i.e. he does t = t + s, where t + s is a concatenation of the strings t and s; * he selects an arbitrary letter of s and removes from s all its occurrences (the selected letter must occur in the string s at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order. Note that after Polycarp finishes the actions, the string s will be empty and the string t will be equal to some value (that is undefined and depends on the order of removing). E.g. consider s="abacaba" so the actions may be performed as follows: * t="abacaba", the letter 'b' is selected, then s="aacaa"; * t="abacabaaacaa", the letter 'a' is selected, then s="c"; * t="abacabaaacaac", the letter 'c' is selected, then s="" (the empty string). You need to restore the initial value of the string s using only the final value of t and find the order of removing letters from s. Input The first line contains one integer T (1 ≀ T ≀ 10^4) β€” the number of test cases. Then T test cases follow. Each test case contains one string t consisting of lowercase letters of the Latin alphabet. The length of t doesn't exceed 5 β‹… 10^5. The sum of lengths of all strings t in the test cases doesn't exceed 5 β‹… 10^5. Output For each test case output in a separate line: * -1, if the answer doesn't exist; * two strings separated by spaces. The first one must contain a possible initial value of s. The second one must contain a sequence of letters β€” it's in what order one needs to remove letters from s to make the string t. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one. Example Input 7 abacabaaacaac nowyouknowthat polycarppoycarppoyarppyarppyrpprppp isi everywherevrywhrvryhrvrhrvhv haaha qweqeewew Output abacaba bac -1 polycarp lcoayrp is si everywhere ewyrhv -1 -1 Note The first test case is considered in the statement.
def func(): t = input() #t = t[:-1] #print(t) s = "" n = len(t) m = 0 sc = [0 for i in range(26)] tc = [0 for i in range(26)] for i in range(n): temp = ord(t[i]) #print(temp) tc[temp - 97] += 1 for i in range(26): if(tc[i]!=0): m += 1 count = m j = n-1 temp = [] for m in range(count,0,-1): i = j while(i>0 and (t[i] in temp)): i -= 1 temp.append(t[i]) an = ord(t[i])-97 if(tc[an] % m): print(-1) return sc[an] = tc[an]/m j = i ansl = 0 for i in range(26): if(sc[i]): ansl += sc[i] #print(ansl) ans = "" s = t[0:int(ansl)] ans += s temp = temp[::-1] ans2 = "".join(temp) #print(ans2) for i in range(len(temp)): c = str(ans2[i]) s = s.replace(c,"") ans += s #print(ans) if(ans!=t): print(-1) return print(t[0:int(ansl)],ans2) t = int(input()) for _ in range(t): func()
It is a simplified version of problem F2. The difference between them is the constraints (F1: k ≀ 2, F2: k ≀ 10). You are given an integer n. Find the minimum integer x such that x β‰₯ n and the number x is k-beautiful. A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing two integers n and k (1 ≀ n ≀ 10^9, 1 ≀ k ≀ 2). Output For each test case output on a separate line x β€” the minimum k-beautiful integer such that x β‰₯ n. Example Input 4 1 1 221 2 177890 2 998244353 1 Output 1 221 181111 999999999
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class C2 { static TreeSet<Long> set1; static TreeSet<Long> set2; private static void sport(int n, int k) { if (k == 1) { Long ceiling = set1.ceiling((long) n); System.out.println(ceiling); } else { Long ceiling = set2.ceiling((long) n); System.out.println(ceiling); } } static void generate(int a, int b, int cnt, long val, TreeSet<Long> set) { if (cnt > 11) { return; } set.add(val); generate(a, b, cnt + 1, val * 10 + a, set); generate(a, b, cnt + 1, val * 10 + b, set); } static void precalc() { for (int i = 0; i < 10; i++) { generate(i, i, 0, 0, set1); } for (int i = 0; i < 10; i++) { for (int j = i; j < 10; j++) { generate(i, j, 0, 0, set2); } } } public static void main(String[] args) { FastScanner sc = new FastScanner(); set1 = new TreeSet<>(); set2 = new TreeSet<>(); precalc(); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int k = sc.nextInt(); sport(n, k); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int[] readArrayInt(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
It is a complicated version of problem F1. The difference between them is the constraints (F1: k ≀ 2, F2: k ≀ 10). You are given an integer n. Find the minimum integer x such that x β‰₯ n and the number x is k-beautiful. A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case consists of one line containing two integers n and k (1 ≀ n ≀ 10^9, 1 ≀ k ≀ 10). Output For each test case output on a separate line x β€” the minimum k-beautiful integer such that x β‰₯ n. Example Input 6 2021 3 177890 2 34512 3 724533 4 998244353 1 12345678 10 Output 2021 181111 34533 724542 999999999 12345678
l=len _,*t=open(0) for p in t: x,k=p.split();k=int(k);n=x while l(set(x))>k:x=str(int(x)+1).strip('0') print(x+(l(n)-l(x))*min(x+'0'*(l(set(x))<k)))
You have a permutation: an array a = [a_1, a_2, …, a_n] of distinct integers from 1 to n. The length of the permutation n is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, f(i), takes a single argument i (1 ≀ i ≀ n-1) and does the following. If a_i > a_{i+1}, the values of a_i and a_{i+1} are exchanged. Otherwise, the permutation doesn't change. The algorithm consists of iterations, numbered with consecutive integers starting with 1. On the i-th iteration, the algorithm does the following: * if i is odd, call f(1), f(3), …, f(n - 2); * if i is even, call f(2), f(4), …, f(n - 1). It can be proven that after a finite number of iterations the permutation will be sorted in increasing order. After how many iterations will this happen for the first time? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 100). Description of the test cases follows. The first line of each test case contains a single integer n (3 ≀ n ≀ 999; n is odd) β€” the length of the permutation. The second line contains n distinct integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” the permutation itself. It is guaranteed that the sum of n over all test cases does not exceed 999. Output For each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time. If the given permutation is already sorted, print 0. Example Input 3 3 3 2 1 7 4 5 7 1 3 2 6 5 1 2 3 4 5 Output 3 5 0 Note In the first test case, the permutation will be changing as follows: * after the 1-st iteration: [2, 3, 1]; * after the 2-nd iteration: [2, 1, 3]; * after the 3-rd iteration: [1, 2, 3]. In the second test case, the permutation will be changing as follows: * after the 1-st iteration: [4, 5, 1, 7, 2, 3, 6]; * after the 2-nd iteration: [4, 1, 5, 2, 7, 3, 6]; * after the 3-rd iteration: [1, 4, 2, 5, 3, 7, 6]; * after the 4-th iteration: [1, 2, 4, 3, 5, 6, 7]; * after the 5-th iteration: [1, 2, 3, 4, 5, 6, 7]. In the third test case, the permutation is already sorted and the answer is 0.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for(int tt = 0 ; tt < t; tt++) { int n = sc.nextInt(); int a[] = new int[n+1]; for(int i = 1; i < n+1; i++)a[i] = sc.nextInt(); long iteration = 0; while(true) { if(isSorted(a))break; else { if((iteration+1) % 2 == 1) { for(int i = 1; i <= n-2; i+=2) { if(a[i] > a[i+1]) { int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } }else { for(int i = 2; i <= n-1; i+=2) { if(a[i] > a[i+1]) { int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } iteration++; } } System.out.println(iteration); } } static boolean isSorted(int a[]) { for(int i =0 ; i < a.length ; i++) { if(a[i] != i)return false; } return true; } public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } public static long max(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public static int max(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public static long min(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public static int min(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public static long sum(long... ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public static long sum(int... ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!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()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Alice and Borys are playing tennis. A tennis match consists of games. In each game, one of the players is serving and the other one is receiving. Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa. Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve. It is known that Alice won a games and Borys won b games during the match. It is unknown who served first and who won which games. Find all values of k such that exactly k breaks could happen during the match between Alice and Borys in total. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^3). Description of the test cases follows. Each of the next t lines describes one test case and contains two integers a and b (0 ≀ a, b ≀ 10^5; a + b > 0) β€” the number of games won by Alice and Borys, respectively. It is guaranteed that the sum of a + b over all test cases does not exceed 2 β‹… 10^5. Output For each test case print two lines. In the first line, print a single integer m (1 ≀ m ≀ a + b + 1) β€” the number of values of k such that exactly k breaks could happen during the match. In the second line, print m distinct integers k_1, k_2, …, k_m (0 ≀ k_1 < k_2 < … < k_m ≀ a + b) β€” the sought values of k in increasing order. Example Input 3 2 1 1 1 0 5 Output 4 0 1 2 3 2 0 2 2 2 3 Note In the first test case, any number of breaks between 0 and 3 could happen during the match: * Alice holds serve, Borys holds serve, Alice holds serve: 0 breaks; * Borys holds serve, Alice holds serve, Alice breaks serve: 1 break; * Borys breaks serve, Alice breaks serve, Alice holds serve: 2 breaks; * Alice breaks serve, Borys breaks serve, Alice breaks serve: 3 breaks. In the second test case, the players could either both hold serves (0 breaks) or both break serves (2 breaks). In the third test case, either 2 or 3 breaks could happen: * Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve: 2 breaks; * Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve: 3 breaks.
#include <bits/stdc++.h> using namespace std; void debugs() { ios_base::sync_with_stdio(false); cin.tie(NULL); } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } long long multiply(long long x, long long res[], long long ressize) { long long carry = 0; for (long long i = 0; i < ressize; i++) { long long product = res[i] * x + carry; res[i] = product % 10; carry = product / 10; } while (carry) { res[ressize] = carry % 10; carry = carry / 10; ressize++; } return ressize; } void bigfactorial(long long n) { long long ressize = 1; long long res[10000]; res[0] = 1; for (long long i = 2; i <= n; i++) { ressize = multiply(i, res, ressize); } for (long long i = ressize - 1; i >= 0; i--) { cout << res[i]; } } bool substring(string s1, string s2) { int M = s1.length(); int N = s2.length(); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (s2[i + j] != s1[j]) break; if (j == M) return true; ; } return false; ; } long long n; bool palindrome(string s) { string t; t = s; reverse(t.begin(), t.end()); if (s == t) { return true; } return false; } bool issafe(vector<vector<long long>> board, long long row, long long col) { for (long long i = 0; i < col; i++) { if (board[row][i]) return false; } for (long long i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 1) return false; } for (long long i = row, j = col; i < n && j < n; i++, j++) { if (board[i][j] == 1) return false; } return true; } void display(vector<vector<long long>> &board) { for (long long i = 0; i < n; i++) { for (long long j = 0; j < n; j++) { cout << board[i][j] << " "; } cout << endl; } } bool solvenqueen(vector<vector<long long>> &board, long long col) { if (col >= n) { return true; } for (long long i = 0; i < n; i++) { if (issafe(board, i, col)) { board[i][col] = 1; if (solvenqueen(board, col + 1)) return true; board[i][col] = 0; } } return false; } int convertstring(string s) { stringstream geek(s); int x = 0; geek >> x; return x; } bool binary(long long k, long long a[]) { long long l = 1; long long r = 1e4; while (l <= r) { long long mid = (l + r) / 2; if (a[mid] == (k)) { return true; } else if (a[mid] > (k)) { r = mid - 1; } else { l = mid + 1; } } return false; } bool notprime(int n) { if (n == 2 || n == 3 || n == 5 || n == 7) { return false; } return true; } int bin(string n) { int num = convertstring(n); int dec_value = 0; int base = 1; int temp = num; while (temp) { int last_digit = temp % 10; temp = temp / 10; dec_value += last_digit * base; base = base * 2; } return dec_value; } bool sorted(int a[], int n) { for (int i = 1; i <= n - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } int main() { long long a, b; cin >> a >> b; int m = ((a + b) / 2) - min(a, b); int maxi = a + b - (((a + b) / 2) - min(a, b)); if ((a + b) % 2 == 0) { cout << (maxi - m) / 2 + 1 << endl; for (int i = m; i <= maxi; i += 2) { cout << i << " "; } cout << endl; } else { cout << maxi - m + 1 << endl; for (int i = m; i <= maxi; i++) { cout << i << " "; } cout << endl; } } }
In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor. On the current level, the hero is facing n caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave i, he will have to fight k_i monsters in a row: first a monster with armor a_{i, 1}, then a monster with armor a_{i, 2} and so on, finally, a monster with armor a_{i, k_i}. The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order. Each time the hero beats a monster, the hero's power increases by 1. Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^5). Description of the test cases follows. The first line of each test case contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of caves. The i-th of the next n lines contains an integer k_i (1 ≀ k_i ≀ 10^5) β€” the number of monsters in the i-th cave, followed by k_i integers a_{i, 1}, a_{i, 2}, …, a_{i, k_i} (1 ≀ a_{i, j} ≀ 10^9) β€” armor levels of the monsters in cave i in order the hero has to fight them. It is guaranteed that the sum of k_i over all test cases does not exceed 10^5. Output For each test case print a single integer β€” the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters. Example Input 2 1 1 42 2 3 10 15 8 2 12 11 Output 43 13 Note In the first test case, the hero has to beat a single monster with armor 42, it's enough to have power 43 to achieve that. In the second test case, the hero can pass the level with initial power 13 as follows: * enter cave 2: * beat a monster with armor 12, power increases to 14; * beat a monster with armor 11, power increases to 15; * enter cave 1: * beat a monster with armor 10, power increases to 16; * beat a monster with armor 15, power increases to 17; * beat a monster with armor 8, power increases to 18.
import os import sys from io import BytesIO, IOBase import math from queue import Queue import collections import itertools import bisect import heapq # sys.setrecursionlimit(100000) # ^^^TAKE CARE FOR MEMORY LIMIT^^^ import random def main(): pass BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def binary(n): return (bin(n).replace("0b", "")) def decimal(s): return (int(s, 2)) def pow2(n): p = 0 while (n > 1): n //= 2 p += 1 return (p) def primeFactors(n): cnt = [] while n % 2 == 0: cnt.append(2) n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: cnt.append(i) n = n / i if n > 2: cnt.append(int(n)) return (cnt) def primeFactorsCount(n): cnt=0 while n % 2 == 0: cnt+=1 n = n // 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: cnt+=1 n = n // i if n > 2: cnt+=1 return (cnt) def isPrime(n): if (n == 1): return (False) else: root = int(n ** 0.5) root += 1 for i in range(2, root): if (n % i == 0): return (False) return (True) def maxPrimeFactors(n): maxPrime = -1 while n % 2 == 0: maxPrime = 2 n >>= 1 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i if n > 2: maxPrime = n return int(maxPrime) def countcon(s, i): c = 0 ch = s[i] for i in range(i, len(s)): if (s[i] == ch): c += 1 else: break return (c) def lis(arr): n = len(arr) lis = [1] * n for i in range(1, n): for j in range(0, i): if arr[i] > arr[j] and lis[i] < lis[j] + 1: lis[i] = lis[j] + 1 maximum = 0 for i in range(n): maximum = max(maximum, lis[i]) return maximum def isSubSequence(str1, str2): m = len(str1) n = len(str2) j = 0 i = 0 while j < m and i < n: if str1[j] == str2[i]: j = j + 1 i = i + 1 return j == m def maxfac(n): root = int(n ** 0.5) for i in range(2, root + 1): if (n % i == 0): return (n // i) return (n) def p2(n): c = 0 while (n % 2 == 0): n //= 2 c += 1 return c def seive(n): primes = [True] * (n + 1) primes[1] = primes[0] = False i = 2 while (i * i <= n): if (primes[i] == True): for j in range(i * i, n + 1, i): primes[j] = False i += 1 pr = [] for i in range(0, n + 1): if (primes[i]): pr.append(i) return pr def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def denofactinverse(n, m): fac = 1 for i in range(1, n + 1): fac = (fac * i) % m return (pow(fac, m - 2, m)) def numofact(n, m): fac = 1 for i in range(1, n + 1): fac = (fac * i) % m return (fac) def sod(n): s = 0 while (n > 0): s += n % 10 n //= 10 return s def CanWin(val): for i in range(0,len(le)): if(val>le[i][0]): val+=le[i][1] else: return False return True for xyz in range(0,int(input())): n=int(input()) le=[] for i in range(0,n): l=list(map(int,input().split())) temp=l[1:] #print(temp) minp=0 for j in range(0,l[0]): minp=max(minp,temp[j]-j+1) le.append((minp,l[0])) le.sort() ps=0 ans=0 for i in range(0,n): ans=max(ans,le[i][0]-ps) ps+=le[i][1] print(ans)
This version of the problem differs from the next one only in the constraint on n. Note that the memory limit in this problem is lower than in others. You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom. You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1. Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds: * Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y. * Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell ⌊ x/z βŒ‹ (x divided by z rounded down). Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding). Input The only line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5; 10^8 < m < 10^9; m is a prime number) β€” the length of the strip and the modulo. Output Print the number of ways to move the token from cell n to cell 1, modulo m. Examples Input 3 998244353 Output 5 Input 5 998244353 Output 25 Input 42 998244353 Output 793019428 Note In the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3. There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2. Therefore, there are five ways in total.
# template begins ##################################### from io import BytesIO, IOBase import sys import math import os import heapq from collections import defaultdict, deque from math import ceil from bisect import bisect_left, bisect_left from time import perf_counter # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") def mint(): return map(int, input().split()) def mfloat(): return map(float, input().split()) def intin(): return int(input()) ##################################### # template ends # Use the recursion snippet if heavy recursion is needed (depth>1000) # If constraints are tight, use 1d arrays instead of 2d, like g[i*m+j] instead of g[i][j] def solve(): n, mod = map(int, input().split()) dp = [0]*(n+1) dp[-1] = 1 # brute force # for i in range(n, 1, -1): # for j in range(1, i): # dp[j] = (dp[j] + dp[i]) % mod # for j in range(2, i+1): # dp[i//j] = (dp[i] + dp[i//j]) % mod # print(dp[1]) """ 2^(n-2) ways by addition alone? yes """ # for i in range(n-1, 0, -1): # by_addition = pow(2, n-i-1, mod) # print("power =", pow(2, n-2, mod)) current = 1 suffix_sum = [0]*(n+1) suffix_sum[-1] = 1 for i in range(n-1, 0, -1): dp[i] = suffix_sum[i+1] # for j in range(2*i, n+1, i): # dp[i] = (dp[i] + suffix_sum[j] - # (suffix_sum[j+j] if j+j < n else 0)) # % mod # break for j in range(2, n+1): if i*j > n: break dp[i] += suffix_sum[i*j] - (suffix_sum[i*j+j] if i*j+j <= n else 0) dp[i] %= mod suffix_sum[i] = (suffix_sum[i+1] + dp[i]) % mod # print(dp) # print(suffix_sum) print(dp[1] % mod) def main(): t = 1 # t = int(input()) for _ in range(t): solve() if __name__ == "__main__": start_time = perf_counter() main() print(perf_counter()-start_time, file=sys.stderr)
Note that the memory limit in this problem is lower than in others. You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom. You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1. Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds: * Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y. * Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell ⌊ x/z βŒ‹ (x divided by z rounded down). Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding). Input The only line contains two integers n and m (2 ≀ n ≀ 4 β‹… 10^6; 10^8 < m < 10^9; m is a prime number) β€” the length of the strip and the modulo. Output Print the number of ways to move the token from cell n to cell 1, modulo m. Examples Input 3 998244353 Output 5 Input 5 998244353 Output 25 Input 42 998244353 Output 793019428 Input 787788 100000007 Output 94810539 Note In the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3. There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2. Therefore, there are five ways in total.
n, m = map(int, input().split()) c = [0]*n + [1] + [0]*n for i in range(n-1, 0, -1): c[i] = 2*c[i+1] % m for j in range(2, n//i + 1): c[i] = (c[i] + c[i*j] - c[(i+1)*j]) % m print((c[1] - c[2]) % m)
You are given two integers l and r, l≀ r. Find the largest possible value of a mod b over all pairs (a, b) of integers for which rβ‰₯ a β‰₯ b β‰₯ l. As a reminder, a mod b is a remainder we get when dividing a by b. For example, 26 mod 8 = 2. Input Each test contains multiple test cases. The first line contains one positive integer t (1≀ t≀ 10^4), denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers l, r (1≀ l ≀ r ≀ 10^9). Output For every test case, output the largest possible value of a mod b over all pairs (a, b) of integers for which rβ‰₯ a β‰₯ b β‰₯ l. Example Input 4 1 1 999999999 1000000000 8 26 1 999999999 Output 0 1 12 499999999 Note In the first test case, the only allowed pair is (a, b) = (1, 1), for which a mod b = 1 mod 1 = 0. In the second test case, the optimal choice is pair (a, b) = (1000000000, 999999999), for which a mod b = 1.
import java.io.*; import java.lang.Math; import java.math.*; import java.util.*; public final class A_The_Miracle_and_the_Sleeper { public static void main(String[] args) throws IOException { int testCases = sc.nextInt(); for (int cases = 0; cases < testCases; cases++) { // My code int l = sc.nextInt(); int r = sc.nextInt(); if (l == r) { out.println(0); continue; } if (l == 1 && r == 2) { out.println(0); continue; } int lowerBound = Math.max(l, r / 2); int maxDiff; if (lowerBound == l) { if (r / 2 == lowerBound) { maxDiff = r - (lowerBound + 1); } else { maxDiff = r - l; } } else { maxDiff = r - (lowerBound + 1); } out.println(maxDiff); } out.flush(); } public static PrintWriter out = new PrintWriter(System.out); public static SuperFast sc = new SuperFast(); static class SuperFast { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public SuperFast() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public SuperFast(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
During the hypnosis session, Nicholas suddenly remembered a positive integer n, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one? For some numbers doing so is impossible: for example, for number 53 it's impossible to delete some of its digits to obtain a not prime integer. However, for all n in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number. Note that you cannot remove all the digits from the number. A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. 1 is neither a prime nor a composite number. Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10^3), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer k (1 ≀ k ≀ 50) β€” the number of digits in the number. The second line of each test case contains a positive integer n, which doesn't contain zeros in decimal notation (10^{k-1} ≀ n < 10^{k}). It is guaranteed that it is always possible to remove less than k digits to make the number not prime. It is guaranteed that the sum of k over all test cases does not exceed 10^4. Output For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions. If there are multiple solutions, print any. Example Input 7 3 237 5 44444 3 221 2 35 3 773 1 4 30 626221626221626221626221626221 Output 2 27 1 4 1 1 2 35 2 77 1 4 1 6 Note In the first test case, you can't delete 2 digits from the number 237, as all the numbers 2, 3, and 7 are prime. However, you can delete 1 digit, obtaining a number 27 = 3^3. In the second test case, you can delete all digits except one, as 4 = 2^2 is a composite number.
def f(a, b): c = (23, 37, 73, 53) return not a * 10 + b in c for _ in range(int(input())): k = int(input()) a = [int(i) for i in input()] c = (1, 4, 6, 8, 9) for i in a: if i in c: print(1) print(i) break else: print(2) if f(a[0], a[1]): print(f'{a[0]}{a[1]}') elif f(a[0], a[2]): print(f'{a[0]}{a[2]}') elif f(a[1], a[2]): print(f'{a[1]}{a[2]}')
Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents β€”there was a pile of different rings: gold and silver... "How am I to tell which is the One?!" the mage howled. "Throw them one by one into the Cracks of Doom and watch when Mordor falls!" Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found n rings. And the i-th ring was either gold or silver. For convenience Saruman wrote down a binary string s of n characters, where the i-th character was 0 if the i-th ring was gold, and 1 if it was silver. Saruman has a magic function f, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, f(001010) = 10, f(111) = 7, f(11011101) = 221. Saruman, however, thinks that the order of the rings plays some important role. He wants to find 2 pairs of integers (l_1, r_1), (l_2, r_2), such that: * 1 ≀ l_1 ≀ n, 1 ≀ r_1 ≀ n, r_1-l_1+1β‰₯ ⌊ n/2 βŒ‹ * 1 ≀ l_2 ≀ n, 1 ≀ r_2 ≀ n, r_2-l_2+1β‰₯ ⌊ n/2 βŒ‹ * Pairs (l_1, r_1) and (l_2, r_2) are distinct. That is, at least one of l_1 β‰  l_2 and r_1 β‰  r_2 must hold. * Let t be the substring s[l_1:r_1] of s, and w be the substring s[l_2:r_2] of s. Then there exists non-negative integer k, such that f(t) = f(w) β‹… k. Here substring s[l:r] denotes s_ls_{l+1}… s_{r-1}s_r, and ⌊ x βŒ‹ denotes rounding the number down to the nearest integer. Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists. Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10^3), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer n (2 ≀ n ≀ 2 β‹… 10^4) β€” length of the string. The second line of each test case contains a non-empty binary string of length n. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For every test case print four integers l_1, r_1, l_2, r_2, which denote the beginning of the first substring, the end of the first substring, the beginning of the second substring, and the end of the second substring, respectively. If there are multiple solutions, print any. Example Input 7 6 101111 9 111000111 8 10000000 5 11011 6 001111 3 101 30 100000000000000100000000000000 Output 3 6 1 3 1 9 4 9 5 8 1 4 1 5 3 5 1 6 2 4 1 2 2 3 1 15 16 30 Note In the first testcase f(t) = f(1111) = 15, f(w) = f(101) = 5. In the second testcase f(t) = f(111000111) = 455, f(w) = f(000111) = 7. In the third testcase f(t) = f(0000) = 0, f(w) = f(1000) = 8. In the fourth testcase f(t) = f(11011) = 27, f(w) = f(011) = 3. In the fifth testcase f(t) = f(001111) = 15, f(w) = f(011) = 3.
#include <bits/stdc++.h> using namespace std; const long long MX = 303030; const long long INF = 9e15; long long tc; vector<long long> v[2]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> tc; while (tc--) { long long n; string s; cin >> n; cin >> s; long long chk[2] = {0}; v[0].clear(); v[1].clear(); for (int i = 0; i < s.size(); i++) { chk[s[i] - '0'] = 1; v[s[i] - '0'].push_back(i); } if ((!chk[0] && chk[1])) { if (n % 2 == 0) { cout << n / 2 + 1 << " " << n << " " << 1 << " " << n / 2 << "\n"; } else { cout << n / 2 + 2 << " " << n << " " << 1 << " " << n / 2 << "\n"; } } else { long long ret = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '0' && n - i - 1 >= n / 2) { cout << i + 1 << " " << n << " " << i + 2 << " " << n << "\n"; ret = 1; break; } } if (!ret) { for (int i = s.size() - 1; i >= 0; i--) { if (s[i] == '0' && i >= n / 2) { cout << 1 << " " << i + 1 << " " << 1 << " " << i << "\n"; break; } } } } } }
This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved. Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine. The main element of this machine are n rods arranged along one straight line and numbered from 1 to n inclusive. Each of these rods must carry an electric charge quantitatively equal to either 1 or -1 (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero. More formally, the rods can be represented as an array of n numbers characterizing the charge: either 1 or -1. Then the condition must hold: a_1 - a_2 + a_3 - a_4 + … = 0, or βˆ‘_{i=1}^n (-1)^{i-1} β‹… a_i = 0. Sparky charged all n rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has q questions. In the ith question Sparky asks: if the machine consisted only of rods with numbers l_i to r_i inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all. If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods. Help your friends and answer all of Sparky's questions! Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10^3), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers n and q (1 ≀ n, q ≀ 3 β‹… 10^5) β€” the number of rods and the number of questions. The second line of each test case contains a non-empty string s of length n, where the charge of the i-th rod is 1 if s_i is the "+" symbol, or -1 if s_i is the "-" symbol. Each next line from the next q lines contains two positive integers l_i ans r_i (1 ≀ l_i ≀ r_i ≀ n) β€” numbers, describing Sparky's questions. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5, and the sum of q over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print a single integer β€” the minimal number of rods that can be removed. Example Input 3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Output 2 2 1 0 1 2 1 2 1 2 1 1 2 1 Note In the first test case for the first query you can remove the rods numbered 5 and 8, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero. In the second test case: * For the first query, we can remove the rods numbered 1 and 11, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. * For the second query we can remove the rod numbered 9, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. * For the third query we can not remove the rods at all.
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, q; cin >> n >> q; string s; cin >> s; vector<int> a = {0}; int x = 0; for (int i = 0; i < n; i++) { int c = 1; if (s[i] == '-') { c = -1; } if (i % 2 == 0) { x += c; } else { x -= c; } a.push_back(x); } for (int i = 0, l, r; i < q; i++) { cin >> l >> r; if ((r - l + 1) % 2) { cout << "1\n"; } else { cout << ((a[r] == a[l - 1]) ? (0) : (2)) << "\n"; } } } }
This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved. Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine. The main element of this machine are n rods arranged along one straight line and numbered from 1 to n inclusive. Each of these rods must carry an electric charge quantitatively equal to either 1 or -1 (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero. More formally, the rods can be represented as an array of n numbers characterizing the charge: either 1 or -1. Then the condition must hold: a_1 - a_2 + a_3 - a_4 + … = 0, or βˆ‘_{i=1}^n (-1)^{i-1} β‹… a_i = 0. Sparky charged all n rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has q questions. In the ith question Sparky asks: if the machine consisted only of rods with numbers l_i to r_i inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Also Sparky wants to know the numbers of these rods. Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all. If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods. Help your friends and answer all of Sparky's questions! Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10^3), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers n and q (1 ≀ n, q ≀ 3 β‹… 10^5) β€” the number of rods and the number of questions. The second line of each test case contains a non-empty string s of length n, where the charge of the i-th rod is 1 if s_i is the "+" symbol, or -1 if s_i is the "-" symbol. Each next line from the next q lines contains two positive integers l_i ans r_i (1 ≀ l_i ≀ r_i ≀ n) β€” numbers, describing Sparky's questions. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5, and the sum of q over all test cases does not exceed 3 β‹… 10^5. It is guaranteed that the sum of the answers (minimal number of rods that can be removed) over all test cases does not exceed 10^6. Output For each test case, print the answer in the following format: In the first line print a single integer k β€” the minimal number of rods that can be removed. In the second line print k numbers separated by a space β€” the numbers of rods to be removed. If there is more than one correct answer, you can print any. Example Input 3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Output 2 5 8 2 1 11 1 9 0 1 1 2 1 2 1 2 2 1 3 1 2 2 2 3 1 3 1 3 2 3 4 1 4 Note In the first test case for the first query you can remove the rods numbered 5 and 8, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero. In the second test case: * For the first query, we can remove the rods numbered 1 and 11, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. * For the second query we can remove the rod numbered 9, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. * For the third query we can not remove the rods at all.
import java.util.*; import java.io.*; public class D1562 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int q = sc.nextInt(); char[] s = sc.next().toCharArray(); int[] val = new int[n]; for (int i = 0; i < val.length; i++) { val[i] = (i % 2 == 0 ? 1 : -1) * (s[i] == '+' ? 1 : -1); if (i != 0) val[i] += val[i - 1]; } TreeSet<Integer>[] values = new TreeSet[2 * n + 1]; for (int i = 0; i < values.length; i++) { values[i] = new TreeSet<Integer>(); } for (int i = 0; i < n; i++) { values[val[i] + n].add(i); } // ArrayList<int[]>[] queries = new ArrayList[n]; // for (int i = 0; i < queries.length; i++) { // queries[i] = new ArrayList<int[]>(); // } // ArrayList<Integer>[] ans = new ArrayList[n]; // for (int i = 0; i < ans.length; i++) { // ans[i] = new ArrayList<Integer>(); // } // System.out.println(Arrays.deepToString(values)); for (int i = 0; i < q; i++) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int sum = val[r] - (l == 0 ? 0 : val[l - 1]); ArrayList<Integer> ans = new ArrayList<Integer>(); if (sum == 0) { } else { if ((r - l + 1) % 2 == 0) { ans.add(l); l++; } sum = val[r] - (l == 0 ? 0 : val[l - 1]); if (sum > 0) { ans.add(values[(l == 0 ? 0 : val[l - 1]) + sum / 2 + 1 + n].ceiling(l)); } else { ans.add(values[(l == 0 ? 0 : val[l - 1]) + sum / 2 - 1 + n].ceiling(l)); } } pw.println(ans.size()); for (int x : ans) { pw.print((x + 1) + " "); } pw.println(); } } pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Morning desert sun horizon Rise above the sands of time... Fates Warning, "Exodus" After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open! Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository. The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences. Suppose a string s_1s_2s_3 … s_n is given. Then its "expansion" is defined as the sequence of strings s_1, s_1 s_2, ..., s_1 s_2 … s_n, s_2, s_2 s_3, ..., s_2 s_3 … s_n, s_3, s_3 s_4, ..., s_{n-1} s_n, s_n. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string s. Here, strings are compared lexicographically. Help Ori with this task! A string a is lexicographically smaller than a string b if and only if one of the following holds: * a is a prefix of b, but a β‰  b; * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10^3), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer n (1 ≀ n ≀ 5000) β€” length of the string. The second line of each test case contains a non-empty string of length n, which consists of lowercase latin letters. It is guaranteed that the sum of n over all test cases does not exceed 10^4. Output For every test case print one non-negative integer β€” the answer to the problem. Example Input 7 5 acbac 8 acabacba 12 aaaaaaaaaaaa 10 abacabadac 8 dcbaabcd 3 cba 6 sparky Output 9 17 12 29 14 3 9 Note In first test case the "expansion" of the string is: 'a', 'ac', 'acb', 'acba', 'acbac', 'c', 'cb', 'cba', 'cbac', 'b', 'ba', 'bac', 'a', 'ac', 'c'. The answer can be, for example, 'a', 'ac', 'acb', 'acba', 'acbac', 'b', 'ba', 'bac', 'c'.
#include <bits/stdc++.h> using namespace std; const int N = 5e3 + 9; const int Log2 = 23; const int inf = 1e9 + 7; vector<int> g[N]; string s; int T, n, lcp[N][N], dp[N][N]; void Repack() { for (int i = 1; i <= n; i++) lcp[i][n + 1] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) dp[i][j] = 0; for (int i = 1; i <= n; i++) dp[1][i] = i; } void out() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cout << dp[i][j] << " "; cout << "\n"; } exit(0); } int main() { ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0); if (fopen("tst" ".INP", "r")) { freopen( "tst" ".INP", "r", stdin); } cin >> T; while (T--) { cin >> n >> s; s = " " + s; Repack(); for (int i = n; i > 0; i--) { for (int j = i - 1; j > 0; j--) { if (s[j] != s[i]) lcp[j][i] = 1; else lcp[j][i] = lcp[j + 1][i + 1] + 1; } } for (int i = 2; i <= n; i++) { int mn = n + 1; for (int j = 1; j <= n; j++) g[j].clear(); for (int j = i - 1; j > 0; j--) { mn = min(mn, lcp[j][i]); g[lcp[j][i]].push_back(j); } for (int j = i; j <= n; j++) dp[i][j] = max(dp[i][j], dp[i][j - 1] + 1); for (int val = 1; val <= n; val++) { for (auto prv : g[val]) { dp[i][i + val - 1] = max(dp[i][i + val - 1], dp[i][i + val - 2] + 1); if (s[i + val - 1] > s[prv + val - 1]) dp[i][i + val - 1] = max(dp[i][i + val - 1], dp[prv][n] + 1); } } for (int j = i; j <= n; j++) dp[i][j] = max(dp[i][j], dp[i][j - 1] + 1); } int ans = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) ans = max(ans, dp[i][j]); cout << ans << "\n"; } }
You are given two positive integers n and s. Find the maximum possible median of an array of n non-negative integers (not necessarily distinct), such that the sum of its elements is equal to s. A median of an array of integers of length m is the number standing on the ⌈ {m/2} βŒ‰-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from 1. For example, a median of the array [20,40,20,50,50,30] is the ⌈ m/2 βŒ‰-th element of [20,20,30,40,50,50], so it is 30. There exist other definitions of the median, but in this problem we use the described definition. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. Each test case contains a single line with two integers n and s (1 ≀ n, s ≀ 10^9) β€” the length of the array and the required sum of the elements. Output For each test case print a single integer β€” the maximum possible median. Example Input 8 1 5 2 5 3 5 2 1 7 17 4 14 1 1000000000 1000000000 1 Output 5 2 2 0 4 4 1000000000 0 Note Possible arrays for the first three test cases (in each array the median is underlined): * In the first test case [\underline{5}] * In the second test case [\underline{2}, 3] * In the third test case [1, \underline{2}, 2]
import java.util.*; import java.io.*; public class A { static HashMap<Integer, Integer> map = new HashMap<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = in.nextInt(); for(int tt = 0; tt < t; tt++) { long n = in.nextLong(), s = in.nextLong(); if (n == 1) { pw.println(s); continue; } long div = ((n / 2) + 1); long res = s / div; pw.println(res); } pw.close(); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
A binary string is a string that consists of characters 0 and 1. Let \operatorname{MEX} of a binary string be the smallest digit among 0, 1, or 2 that does not occur in the string. For example, \operatorname{MEX} of 001011 is 2, because 0 and 1 occur in the string at least once, \operatorname{MEX} of 1111 is 0, because 0 and 2 do not occur in the string and 0 < 2. A binary string s is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring β€” the whole string. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. What is the minimal sum of \operatorname{MEX} of all substrings pieces can be? Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. Each test case contains a single binary string s (1 ≀ |s| ≀ 10^5). It's guaranteed that the sum of lengths of s over all test cases does not exceed 10^5. Output For each test case print a single integer β€” the minimal sum of \operatorname{MEX} of all substrings that it is possible to get by cutting s optimally. Example Input 6 01 1111 01100 101 0000 01010 Output 1 0 2 1 1 2 Note In the first test case the minimal sum is \operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1. In the second test case the minimal sum is \operatorname{MEX}(1111) = 0. In the third test case the minimal sum is \operatorname{MEX}(01100) = 2.
import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from collections import Counter from collections import defaultdict as dd # sys.setrecursionlimit(100000000) flush = lambda: stdout.flush() stdstr = lambda: stdin.readline() stdint = lambda: int(stdin.readline()) stdpr = lambda x: stdout.write(str(x)) stdmap = lambda: map(int, stdstr().split()) stdarr = lambda: list(map(int, stdstr().split())) mod = 1000000007 for _ in range(stdint()): s = input() split = [[s[0]]] for i in range(1, len(s)): if(s[i] == split[-1][-1]): split[-1].append(s[i]) else: split.append([s[i]]) if(len(split) == 1): if(split[0][0] == "1"): print(0) else: print(1) elif(len(split) == 2): print(1) else: zeroGroups = 0 for i in split: if(i[0] == "0"): zeroGroups += 1 print(min(2, zeroGroups))
A binary string is a string that consists of characters 0 and 1. A bi-table is a table that has exactly two rows of equal length, each being a binary string. Let \operatorname{MEX} of a bi-table be the smallest digit among 0, 1, or 2 that does not occur in the bi-table. For example, \operatorname{MEX} for \begin{bmatrix} 0011\\\ 1010 \end{bmatrix} is 2, because 0 and 1 occur in the bi-table at least once. \operatorname{MEX} for \begin{bmatrix} 111\\\ 111 \end{bmatrix} is 0, because 0 and 2 do not occur in the bi-table, and 0 < 2. You are given a bi-table with n columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table β€” the whole bi-table. What is the maximal sum of \operatorname{MEX} of all resulting bi-tables can be? Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of the description of each test case contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of columns in the bi-table. Each of the next two lines contains a binary string of length n β€” the rows of the bi-table. It's guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print a single integer β€” the maximal sum of \operatorname{MEX} of all bi-tables that it is possible to get by cutting the given bi-table optimally. Example Input 4 7 0101000 1101100 5 01100 10101 2 01 01 6 000000 111111 Output 8 8 2 12 Note In the first test case you can cut the bi-table as follows: * \begin{bmatrix} 0\\\ 1 \end{bmatrix}, its \operatorname{MEX} is 2. * \begin{bmatrix} 10\\\ 10 \end{bmatrix}, its \operatorname{MEX} is 2. * \begin{bmatrix} 1\\\ 1 \end{bmatrix}, its \operatorname{MEX} is 0. * \begin{bmatrix} 0\\\ 1 \end{bmatrix}, its \operatorname{MEX} is 2. * \begin{bmatrix} 0\\\ 0 \end{bmatrix}, its \operatorname{MEX} is 1. * \begin{bmatrix} 0\\\ 0 \end{bmatrix}, its \operatorname{MEX} is 1. The sum of \operatorname{MEX} is 8.
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); String s1=sc.next(); String s2=sc.next(); int ans=0; for(int i=0;i<n;i++) { int a=s1.charAt(i)-'0'; int b=s2.charAt(i)-'0'; if((a^b)==1)ans+=2; else { if(i+1<n) { int c=s1.charAt(i+1)-'0'; int d=s2.charAt(i+1)-'0'; if((a^c)==1||(a^d)==1) { ans+=2; if(a==0&&(c^d)==1)ans++; i++; } else { if(a==0)ans++; } } else { if(a==0)ans++; } } } System.out.println(ans); } } }
It is the easy version of the problem. The only difference is that in this version n = 1. In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 ≀ k ≀ n. 1| 2| β‹…β‹…β‹…| m - 1| m ---|---|---|---|--- m + 1| m + 2| β‹…β‹…β‹…| 2 m - 1| 2 m 2m + 1| 2m + 2| β‹…β‹…β‹…| 3 m - 1| 3 m \vdots| \vdots| \ddots| \vdots| \vdots m (n - 1) + 1| m (n - 1) + 2| β‹…β‹…β‹…| n m - 1| n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person. It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j. After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through. Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3. Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied). Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two integers n and m (n = 1, 1 ≀ m ≀ 300) β€” the number of rows and places in each row respectively. The second line of each test case contains n β‹… m integers a_1, a_2, …, a_{n β‹… m} (1 ≀ a_i ≀ 10^9), where a_i is the sight level of i-th person. It's guaranteed that the sum of n β‹… m over all test cases does not exceed 10^5. Output For each test case print a single integer β€” the minimal total inconvenience that can be achieved. Example Input 4 1 3 1 2 3 1 5 2 1 5 3 3 1 2 2 1 1 6 2 3 2 1 1 1 Output 3 6 0 1 Note In the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be 0, inconvenience of the second person will be 1 and inconvenience of the third person will be 2. The total inconvenience is 0 + 1 + 2 = 3. In the second test case, people should sit as follows: s_1 = 2, s_2 = 1, s_3 = 5, s_4 = 4, s_5 = 3. The total inconvenience will be 6.
#include <bits/stdc++.h> using namespace std; void solve() { long long int n, m, i, j, k, l; cin >> n >> m; long long int a[m + 2]; for (i = 0; i < m; i++) { cin >> a[i]; } long long int ct = 0; for (i = 0; i < m; i++) { long long int cc = a[i]; long long int vc = 0; for (j = 0; j < i; j++) { if (a[j] < cc) vc++; } ct += vc; } cout << ct << endl; } int main() { int t, tc; cin >> tc; while (tc--) { solve(); } return 0; }
It is the hard version of the problem. The only difference is that in this version 1 ≀ n ≀ 300. In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 ≀ k ≀ n. 1| 2| β‹…β‹…β‹…| m - 1| m ---|---|---|---|--- m + 1| m + 2| β‹…β‹…β‹…| 2 m - 1| 2 m 2m + 1| 2m + 2| β‹…β‹…β‹…| 3 m - 1| 3 m \vdots| \vdots| \ddots| \vdots| \vdots m (n - 1) + 1| m (n - 1) + 2| β‹…β‹…β‹…| n m - 1| n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person. It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j. After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through. Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3. Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied). Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two integers n and m (1 ≀ n, m ≀ 300) β€” the number of rows and places in each row respectively. The second line of each test case contains n β‹… m integers a_1, a_2, …, a_{n β‹… m} (1 ≀ a_i ≀ 10^9), where a_i is the sight level of i-th person. It's guaranteed that the sum of n β‹… m over all test cases does not exceed 10^5. Output For each test case print a single integer β€” the minimal total inconvenience that can be achieved. Example Input 7 1 2 1 2 3 2 1 1 2 2 3 3 3 3 3 4 4 1 1 1 1 1 2 2 2 1 1 2 1 4 2 50 50 50 50 3 50 50 50 4 2 6 6 6 6 2 2 9 6 2 9 1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3 Output 1 0 4 0 0 0 1 Note In the first test case, there is a single way to give seats: the first person sits in the first place and the second person β€” in the second. The total inconvenience is 1. In the second test case the optimal seating looks like this: <image> In the third test case the optimal seating looks like this: <image> The number in a cell is the person's index that sits on this place.
import os, sys from io import BytesIO, IOBase from collections import * class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class dict(dict): def __missing__(self, key): return [] class segmenttree: def __init__(self, arr, n): self.tree, self.n = [0] * (2 * n), n # get interval[l,r) def query(self, l, r): res = 0 l += self.n r += self.n while l < r: if l & 1: res += self.tree[l] l += 1 if r & 1: r -= 1 res += self.tree[r] l >>= 1 r >>= 1 return res def update(self, ix, val): ix += self.n # set new value self.tree[ix] = val # move up while ix > 1: self.tree[ix >> 1] = self.tree[ix] + self.tree[ix ^ 1] ix >>= 1 sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)] inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)] inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp(dtype))] inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)] ceil1 = lambda a, b: (a + b - 1) // b for _ in range(int(input())): n, m = inp(int) a, mem, ans = inp(int), defaultdict(lambda: deque([[]])), 0 tem, seat = sorted(a.copy()), segmenttree([], n * m) for i in range(n * m): if i % m == 0: mem[tem[i]].append([]) mem[tem[i]][-1].append(i) for i in range(n * m): while not mem[a[i]][0]: mem[a[i]].popleft() ix = mem[a[i]][0].pop() ans += seat.query(ix - (ix % m), ix) seat.update(ix, 1) # print(ans, seat.tree, mem) print(ans)
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied: * it is not a root, * it has at least one child, and * all its children are leaves. You are given a rooted tree with n vertices. The vertex 1 is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud. What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)? Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer n (2 ≀ n ≀ 2 β‹… 10^5) β€” the number of the vertices in the given tree. Each of the next n-1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v) meaning that there is an edge between vertices u and v in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case print a single integer β€” the minimal number of leaves that is possible to get after some operations. Example Input 5 7 1 2 1 3 1 4 2 5 2 6 4 7 6 1 2 1 3 2 4 2 5 3 6 2 1 2 7 7 3 1 5 1 3 4 6 4 7 2 1 6 2 1 2 3 4 5 3 4 3 6 Output 2 2 1 2 1 Note In the first test case the tree looks as follows: <image> Firstly you can choose a bud vertex 4 and re-hang it to vertex 3. After that you can choose a bud vertex 2 and re-hang it to vertex 7. As a result, you will have the following tree with 2 leaves: <image> It can be proved that it is the minimal number of leaves possible to get. In the second test case the tree looks as follows: <image> You can choose a bud vertex 3 and re-hang it to vertex 5. As a result, you will have the following tree with 2 leaves: <image> It can be proved that it is the minimal number of leaves possible to get.
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<vector<int>> graph(n + 1); for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; graph[u].push_back(v); graph[v].push_back(u); } int ans = 0; int cnt = 0; int flag = 0; function<int(int, int, int)> dfs = [&](int u, int k, int fa) { int is_leaf = 1; int sub_sum = 0; for (auto &v : graph[u]) { if (v == fa) { continue; } is_leaf = 0; sub_sum += dfs(v, k + 1, u); } if (is_leaf) { if (k == 1) { ans++; flag = 1; } return 1; } if (sub_sum == 0) { if (k == 1) { ans++; flag = 1; } return 1; } if (k) { ans += sub_sum; cnt++; } return 0; }; dfs(1, 0, 0); if (flag) { cout << ans - cnt << endl; } else { cout << ans - cnt + 1 << endl; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while (t--) { solve(); } return 0; }
There are n points and m segments on the coordinate line. The initial coordinate of the i-th point is a_i. The endpoints of the j-th segment are l_j and r_j β€” left and right endpoints, respectively. You can move the points. In one move you can move any point from its current coordinate x to the coordinate x - 1 or the coordinate x + 1. The cost of this move is 1. You should move the points in such a way that each segment is visited by at least one point. A point visits the segment [l, r] if there is a moment when its coordinate was on the segment [l, r] (including endpoints). You should find the minimal possible total cost of all moves such that all segments are visited. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of points and segments respectively. The next line contains n distinct integers a_1, a_2, …, a_n (-10^9 ≀ a_i ≀ 10^9) β€” the initial coordinates of the points. Each of the next m lines contains two integers l_j, r_j (-10^9 ≀ l_j ≀ r_j ≀ 10^9) β€” the left and the right endpoints of the j-th segment. It's guaranteed that the sum of n and the sum of m over all test cases does not exceed 2 β‹… 10^5. Output For each test case print a single integer β€” the minimal total cost of all moves such that all segments are visited. Example Input 2 4 11 2 6 14 18 0 3 4 5 11 15 3 5 10 13 16 16 1 4 8 12 17 19 7 13 14 19 4 12 -9 -16 12 3 -20 -18 -14 -13 -10 -7 -3 -1 0 4 6 11 7 9 8 10 13 15 14 18 16 17 18 19 Output 5 22 Note In the first test case the points can be moved as follows: * Move the second point from the coordinate 6 to the coordinate 5. * Move the third point from the coordinate 14 to the coordinate 13. * Move the fourth point from the coordinate 18 to the coordinate 17. * Move the third point from the coordinate 13 to the coordinate 12. * Move the fourth point from the coordinate 17 to the coordinate 16. The total cost of moves is 5. It is easy to see, that all segments are visited by these movements. For example, the tenth segment ([7, 13]) is visited after the second move by the third point. Here is the image that describes the first test case: <image>
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Deque; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collection; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.io.UncheckedIOException; import java.util.stream.Stream; import java.io.Closeable; import java.util.Comparator; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FPointsMovement solver = new FPointsMovement(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class FPointsMovement { Debug debug = new Debug(false); Point[] pts; int ptIter = 0; long inf = (long) 1e15; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int m = in.ri(); pts = new Point[n + 2]; Line[] lines = new Line[m]; for (int i = 0; i < n; i++) { pts[i] = new Point(); pts[i].l = in.ri(); } pts[n] = new Point(); pts[n].l = -inf; pts[n + 1] = new Point(); pts[n + 1].l = inf; for (int i = 0; i < m; i++) { lines[i] = new Line(); lines[i].l = in.ri(); lines[i].r = in.ri(); } n += 2; Arrays.sort(pts, Comparator.comparingLong(x -> x.l)); Arrays.sort(lines, Comparator.<Line>comparingLong(x -> x.l).thenComparingLong(x -> -x.r)); Deque<Line> filterList = new ArrayDeque<>(); for (Line line : lines) { while (!filterList.isEmpty() && filterList.peekLast().r >= line.r) { Line removed = filterList.removeLast(); debug.debug("removed", removed); continue; } filterList.addLast(line); } ptIter = 0; lines = filterList.stream().filter(line -> { while (ptIter < pts.length && pts[ptIter].l < line.l) { ptIter++; } return ptIter == pts.length || pts[ptIter].l > line.r; }).toArray(i -> new Line[i]); m = lines.length; debug.debug("lines", lines); debug.debug("pts", pts); int lIter = 0; for (int i = 0; i < n - 1; i++) { Point cur = pts[i]; Point next = pts[i + 1]; int begin = lIter; while (lIter < m && lines[lIter].l < next.l) { lIter++; } cur.follow = Arrays.copyOfRange(lines, begin, lIter); } long[][] ans = dac(0, n - 1); long best = inf; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { best = Math.min(best, ans[i][j]); } } out.println(best); } public long take(Line[] lines, Point lp, Point rp, int ltake, int rtake) { if (lines.length == 0) { return 0; } long best = Math.min((rp.l - lines[0].r) * rtake, (lines[lines.length - 1].l - lp.l) * ltake); for (int i = 0; i + 1 < lines.length; i++) { best = Math.min(best, (lines[i].l - lp.l) * ltake + (rp.l - lines[i + 1].r) * rtake); } return best; } public long[][] merge(long[][] a, long[][] b, Point lp, Point rp) { long[][] ans = new long[2][2]; Line[] lines = lp.follow; SequenceUtils.deepFill(ans, inf); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { for (int t = 0; t < 2; t++) { long cost = a[i][j] + b[k][t] + take(lines, lp, rp, j + 1, k + 1); ans[i][t] = Math.min(ans[i][t], cost); } } } } return ans; } public long[][] dac(int l, int r) { if (l == r) { long[][] ans = new long[2][2]; ans[0][0] = ans[1][1] = inf; return ans; } int m = (l + r) / 2; long[][] L = dac(l, m); long[][] R = dac(m + 1, r); long[][] ans = merge(L, R, pts[m], pts[m + 1]); debug.debug("l", l); debug.debug("r", r); debug.debug("ans", ans); return ans; } } static class SequenceUtils { public static void deepFill(Object array, long val) { if (array == null) { return; } if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] longArray = (long[]) array; Arrays.fill(longArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } } static class Point { long l; Line[] follow; public String toString() { return "Point{" + "l=" + l + '}'; } } static class Line extends Point { long r; public String toString() { return "Line{" + "r=" + r + ", l=" + l + '}'; } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, int x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private OutputStream writer; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); private static Field stringBuilderValueField; private char[] charBuf = new char[THRESHOLD * 2]; private byte[] byteBuf = new byte[THRESHOLD * 2]; static { try { stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value"); stringBuilderValueField.setAccessible(true); } catch (Exception e) { stringBuilderValueField = null; } stringBuilderValueField = null; } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(OutputStream writer) { this.writer = writer; } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { if (stringBuilderValueField != null) { try { byte[] value = (byte[]) stringBuilderValueField.get(cache); writer.write(value, 0, cache.length()); } catch (Exception e) { stringBuilderValueField = null; } } if (stringBuilderValueField == null) { int n = cache.length(); if (n > byteBuf.length) { //slow writer.write(cache.toString().getBytes(StandardCharsets.UTF_8)); // writer.append(cache); } else { cache.getChars(0, n, charBuf, 0); for (int i = 0; i < n; i++) { byteBuf[i] = (byte) charBuf[i]; } writer.write(byteBuf, 0, n); } } writer.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { writer.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
You are given an undirected weighted graph, consisting of n vertices and m edges. Some queries happen with this graph: * Delete an existing edge from the graph. * Add a non-existing edge to the graph. At the beginning and after each query, you should find four different vertices a, b, c, d such that there exists a path between a and b, there exists a path between c and d, and the sum of lengths of two shortest paths from a to b and from c to d is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path. Input The first line contains two integers n and m (4 ≀ n, m ≀ 10^5) β€” the number of vertices and edges in the graph respectively. Each of the next m lines contain three integers v, u, w (1 ≀ v, u ≀ n, v β‰  u, 1 ≀ w ≀ 10^9) β€” this triple means that there is an edge between vertices v and u with weight w. The next line contains a single integer q (0 ≀ q ≀ 10^5) β€” the number of queries. The next q lines contain the queries of two types: * 0 v u β€” this query means deleting an edge between v and u (1 ≀ v, u ≀ n, v β‰  u). It is guaranteed that such edge exists in the graph. * 1 v u w β€” this query means adding an edge between vertices v and u with weight w (1 ≀ v, u ≀ n, v β‰  u, 1 ≀ w ≀ 10^9). It is guaranteed that there was no such edge in the graph. It is guaranteed that the initial graph does not contain multiple edges. At the beginning and after each query, the graph doesn't need to be connected. It is guaranteed that at each moment the number of edges will be at least 4. It can be proven, that at each moment there exist some four vertices a, b, c, d such that there exists a path between vertices a and b, and there exists a path between vertices c and d. Output Print q + 1 integers β€” the minimal sum of lengths of shortest paths between chosen pairs of vertices before the queries and after each of them. Example Input 6 6 1 3 6 4 3 1 1 4 1 2 6 4 2 4 2 5 4 3 4 1 2 5 2 0 1 4 0 3 4 1 6 1 3 Output 4 3 3 7 5 Note Before the queries you can choose vertices (a, b) = (3, 2) and (c, d) = (1, 4). The sum of lengths of two shortest paths is 3 + 1 = 4. After the first query you can choose vertices (a, b) = (2, 5) and (c, d) = (1, 4). The sum of lengths of two shortest paths is 2 + 1 = 3. After the second query you can choose vertices (a, b) = (3, 4) and (c, d) = (2, 5). The sum of lengths of two shortest paths is 1 + 2 = 3. After the third query, you can choose vertices (a, b) = (2, 6) and (c, d) = (4, 5). The sum of lengths of two shortest paths is 4 + 3 = 7. After the last query you can choose vertices (a, b) = (1, 6) and (c, d) = (2, 5). The sum of lengths of two shortest paths is 3 + 2 = 5.
#include <bits/stdc++.h> using namespace std; const int N = 100005; int n, m; long long s3[N]; map<pair<int, int>, int> mpw, mpc; set<pair<int, int> > G[N], T[N]; set<pair<int, pair<int, int> > > st; set<pair<long long, int> > st3; inline void mdf_edge(int u, int v, int w, int d) { if (u > v) swap(u, v); int lst = mpc[make_pair(u, v)]; mpc[make_pair(u, v)] += d; int cur = mpc[make_pair(u, v)]; if (lst == 2 && cur < 2) st.erase(make_pair(w, make_pair(u, v))); if (lst < 2 && cur == 2) st.insert(make_pair(w, make_pair(u, v))); } inline void add_ver(int u, int v, int w) { auto p = make_pair(w, v); if (G[u].size() < 3) { G[u].insert(p); mdf_edge(u, v, w, 1); if (G[u].size() == 3) { s3[u] = 0; for (auto q : G[u]) s3[u] += q.first; st3.insert(make_pair(s3[u], u)); } } else { auto it = prev(G[u].end()); if (*it < p) { T[u].insert(p); } else { G[u].insert(p); mdf_edge(u, it->second, it->first, -1); mdf_edge(u, v, w, 1); T[u].insert(*it); G[u].erase(it); st3.erase(make_pair(s3[u], u)); s3[u] = 0; for (auto q : G[u]) s3[u] += q.first; st3.insert(make_pair(s3[u], u)); } } } inline void del_ver(int u, int v, int w) { if (T[u].count(make_pair(w, v))) { T[u].erase(make_pair(w, v)); } else { st3.erase(make_pair(s3[u], u)); G[u].erase(make_pair(w, v)); mdf_edge(u, v, w, -1); if (T[u].size()) { auto it = T[u].begin(); mdf_edge(u, it->second, it->first, 1); G[u].insert(*it); T[u].erase(it); s3[u] = 0; for (auto q : G[u]) s3[u] += q.first; st3.insert(make_pair(s3[u], u)); } } } inline void add_edge(int u, int v, int w) { mpw[make_pair(u, v)] = w; mpc[make_pair(u, v)] = 0; add_ver(u, v, w); add_ver(v, u, w); } inline void del_edge(int u, int v, int w) { del_ver(u, v, w); del_ver(v, u, w); } inline long long calc() { long long ret = 1e18; if (st3.size()) ret = min(ret, st3.begin()->first); auto it = st.begin(); vector<pair<int, pair<int, int> > > vec; for (int i = 0; i < min((int)st.size(), 6); i++, ++it) { vec.push_back(*it); } for (int i = 0; i < (int)vec.size(); i++) for (int j = i + 1; j < (int)vec.size(); j++) { if (vec[i].second.first != vec[j].second.first && vec[i].second.first != vec[j].second.second && vec[i].second.second != vec[j].second.first && vec[i].second.second != vec[j].second.second) ret = min(ret, 1ll * vec[i].first + vec[j].first); } return ret; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); if (u > v) swap(u, v); add_edge(u, v, w); } printf("%lld\n", calc()); int q; scanf("%d", &q); while (q--) { int ty, u, v, w; scanf("%d%d%d", &ty, &u, &v); if (u > v) swap(u, v); if (ty) scanf("%d", &w), add_edge(u, v, w); else w = mpw[make_pair(u, v)], del_edge(u, v, w); printf("%lld\n", calc()); } return 0; }
This is an interactive problem. You are given two integers c and n. The jury has a randomly generated set A of distinct positive integers not greater than c (it is generated from all such possible sets with equal probability). The size of A is equal to n. Your task is to guess the set A. In order to guess it, you can ask at most ⌈ 0.65 β‹… c βŒ‰ queries. In each query, you choose a single integer 1 ≀ x ≀ c. As the answer to this query you will be given the [bitwise xor sum](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all y, such that y ∈ A and gcd(x, y) = 1 (i.e. x and y are coprime). If there is no such y this xor sum is equal to 0. You can ask all queries at the beginning and you will receive the answers to all your queries. After that, you won't have the possibility to ask queries. You should find any set A', such that |A'| = n and A' and A have the same answers for all c possible queries. Input Firstly you are given two integers c and n (100 ≀ c ≀ 10^6, 0 ≀ n ≀ c). Interaction In the first line you should print an integer q (0 ≀ q ≀ ⌈ 0.65 β‹… c βŒ‰) β€” the number of queries you want to ask. After that in the same line print q integers x_1, x_2, …, x_q (1 ≀ x_i ≀ c) β€” the queries. For these queries you should read q integers, i-th of them is the answer to the described query for x = x_i. After that you should print n distinct integers A'_1, A'_2, …, A'_n β€” the set A' you found. If there are different sets A' that have the same answers for all possible queries, print any of them. If you will ask more than ⌈ 0.65 β‹… c βŒ‰ queries or if the queries will be invalid, the interactor will terminate immediately and your program will receive verdict Wrong Answer. After printing the queries and answers do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * Read documentation for other languages. Hacks You cannot make hacks in this problem. Example Input 10 6 1 4 2 11 4 4 4 Output 7 10 2 3 5 7 1 6 1 4 5 6 8 10 Note The sample is made only for you to understand the interaction protocol. Your solution will not be tested on the sample. In the sample A = \{1, 4, 5, 6, 8, 10\}. 7 queries are made, 7 ≀ ⌈ 0.65 β‹… 10 βŒ‰ = 7, so the query limit is not exceeded. Answers for the queries: * For 10: 1 is the only number in the set A coprime with 10, so the answer is 1 * For 2: 1_{10} βŠ• 5_{10} = 001_2 βŠ• 101_2 = 4_{10}, where βŠ• is the bitwise xor * For 3: 1_{10} βŠ• 4_{10} βŠ• 5_{10} βŠ• 8_{10} βŠ• 10_{10} = 0001_2 βŠ• 0100_2 βŠ• 0101_2 βŠ• 1000_2 βŠ• 1010_2 = 2_{10} * For 5: 1_{10} βŠ• 4_{10} βŠ• 6_{10} βŠ• 8_{10} = 0001_2 βŠ• 0100_2 βŠ• 0110_2 βŠ• 1000_2 = 11_{10} * For 7: 1_{10} βŠ• 4_{10} βŠ• 5_{10} βŠ• 6_{10} βŠ• 8_{10} βŠ• 10_{10} = 0001_2 βŠ• 0100_2 βŠ• 0101_2 βŠ• 0110_2 βŠ• 1000_2 βŠ• 1010_2 = 4_{10} * For 1: 1_{10} βŠ• 4_{10} βŠ• 5_{10} βŠ• 6_{10} βŠ• 8_{10} βŠ• 10_{10} = 0001_2 βŠ• 0100_2 βŠ• 0101_2 βŠ• 0110_2 βŠ• 1000_2 βŠ• 1010_2 = 4_{10} * For 6: 1_{10} βŠ• 5_{10} = 0001_2 βŠ• 0101_2 = 4_{10}
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.arraycopy; import static java.lang.System.exit; import static java.util.Arrays.copyOf; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.BitSet; import java.util.NoSuchElementException; import java.util.Random; import java.util.StringTokenizer; public class H { static class IntList { int data[] = new int[3]; int size = 0; boolean isEmpty() { return size == 0; } int size() { return size; } int get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return data[index]; } void clear() { size = 0; } void set(int index, int value) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } data[index] = value; } void expand() { if (size >= data.length) { data = copyOf(data, (data.length << 1) + 1); } } void insert(int index, int value) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } expand(); arraycopy(data, index, data, index + 1, size++ - index); data[index] = value; } int delete(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } int value = data[index]; arraycopy(data, index + 1, data, index, --size - index); return value; } void push(int value) { expand(); data[size++] = value; } int pop() { if (size == 0) { throw new NoSuchElementException(); } return data[--size]; } void unshift(int value) { expand(); arraycopy(data, 0, data, 1, size++); data[0] = value; } int shift() { if (size == 0) { throw new NoSuchElementException(); } int value = data[0]; arraycopy(data, 1, data, 0, --size); return value; } } static class LongList { long data[] = new long[3]; int size = 0; boolean isEmpty() { return size == 0; } int size() { return size; } long get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return data[index]; } void clear() { size = 0; } void set(int index, long value) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } data[index] = value; } void expand() { if (size >= data.length) { data = copyOf(data, (data.length << 1) + 1); } } void insert(int index, long value) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } expand(); arraycopy(data, index, data, index + 1, size++ - index); data[index] = value; } long delete(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } long value = data[index]; arraycopy(data, index + 1, data, index, --size - index); return value; } void push(long value) { expand(); data[size++] = value; } long pop() { if (size == 0) { throw new NoSuchElementException(); } return data[--size]; } void unshift(long value) { expand(); arraycopy(data, 0, data, 1, size++); data[0] = value; } long shift() { if (size == 0) { throw new NoSuchElementException(); } long value = data[0]; arraycopy(data, 1, data, 0, --size); return value; } } static void sortBy(int a[], int n, int v[]) { if (n == 0) { return; } for (int i = 1; i < n; i++) { int j = i; int ca = a[i]; int cv = v[ca]; do { int nj = (j - 1) >> 1; int na = a[nj]; if (cv <= v[na]) { break; } a[j] = na; j = nj; } while (j != 0); a[j] = ca; } int ca = a[0]; for (int i = n - 1; i > 0; i--) { int j = 0; while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) { j <<= 1; j += (v[a[j + 2]] > v[a[j + 1]]) ? 2 : 1; } if ((j << 1) + 2 == i) { j = (j << 1) + 1; } int na = a[i]; a[i] = ca; ca = na; int cv = v[ca]; while (j != 0 && v[a[j]] < cv) { j = (j - 1) >> 1; } while (j != 0) { na = a[j]; a[j] = ca; ca = na; j = (j - 1) >> 1; } } a[0] = ca; } static void solve() throws Exception { int c = scanInt(), n = scanInt(); int lc[] = new int[c + 1]; for (int i = 1; i * i <= c; i++) { for (int j = i; j * i <= c; j += i) { lc[j * i] = j; } } for (int i = 4; i <= c; i++) { lc[i] = lc[lc[i]]; } int q = 0, x[] = new int[c]; for (int i = 1; i <= c; i++) { if (lc[i] == i) { x[q++] = i; } } IntList cls[] = new IntList[q]; for (int i = 0; i < q; i++) { cls[i] = new IntList(); } int lcr[] = new int[c + 1]; for (int i = 0; i < q; i++) { lcr[x[i]] = i; } for (int i = 1; i <= c; i++) { cls[lcr[lc[i]]].push(i); } out.print(q); for (int i = 0; i < q; i++) { out.print(' '); out.print(x[i]); } out.println(); out.flush(); int y[] = new int[c + 1]; for (int i = 0; i < q; i++) { y[x[i]] = scanInt(); } for (int i = c; i >= 1; i--) { if (lc[i] != i) { continue; } for (int j = i + i; j <= c; j += i) { if (lc[j] != j) { continue; } y[j] ^= y[i]; } } for (int i = 1; i <= c; i++) { if (lc[i] != i) { continue; } for (int j = i + i; j <= c; j += i) { if (lc[j] != j) { continue; } y[i] ^= y[j]; } } IntList ca = new IntList(); LongList cb = new LongList(); boolean ans[] = new boolean[c + 1]; int ansN = 0; long lzeros[][] = new long[q][]; BitSet bitZeros[][] = new BitSet[q][]; int nZeros[] = new int[q]; for (int i = 0; i < q; i++) { int cv = y[x[i]]; IntList ccl = cls[i]; int cn = ccl.size; if (cn < 64) { long cans = 0; ca.size = cb.size = cn; while (ca.data.length < cn) { ca.expand(); } while (cb.data.length < cn) { cb.expand(); } arraycopy(ccl.data, 0, ca.data, 0, cn); for (int j = 0; j < cn; j++) { cb.data[j] = 1L << j; } for (int bit = 19; bit >= 0; bit--) { int j; for (j = 0; j < cn; j++) { if ((ca.data[j] & (-1 << bit)) == 1 << bit) { break; } } if (j == cn) { if ((cv & (1 << bit)) != 0) { throw new AssertionError(); } continue; } if ((cv & (1 << bit)) != 0) { cv ^= ca.data[j]; cans ^= cb.data[j]; } for (int jj = 0; jj < cn; jj++) { if (jj != j && (ca.data[jj] & (1 << bit)) != 0) { ca.data[jj] ^= ca.data[j]; cb.data[jj] ^= cb.data[j]; } } } for (int j = 0; j < cn; j++) { if ((cans & (1L << j)) != 0) { ans[ccl.data[j]] = true; ++ansN; } } int nz = 0; for (int j = 0; j < cn; j++) { if (ca.data[j] == 0) { ++nz; } } nZeros[i] = nz; lzeros[i] = new long[nz]; nz = 0; for (int j = 0; j < cn; j++) { if (ca.data[j] == 0) { lzeros[i][nz++] = cb.data[j]; } } } else { BitSet cans = new BitSet(); ca.size = cn; while (ca.data.length < cn) { ca.expand(); } arraycopy(ccl.data, 0, ca.data, 0, cn); BitSet ccb[] = new BitSet[cn]; for (int j = 0; j < cn; j++) { ccb[j] = new BitSet(); ccb[j].set(j); } for (int bit = 19; bit >= 0; bit--) { int j; for (j = 0; j < cn; j++) { if ((ca.data[j] & (-1 << bit)) == 1 << bit) { break; } } if (j == cn) { if ((cv & (1 << bit)) != 0) { throw new AssertionError(); } continue; } if ((cv & (1 << bit)) != 0) { cv ^= ca.data[j]; cans.xor(ccb[j]); } for (int jj = 0; jj < cn; jj++) { if (jj != j && (ca.data[jj] & (1 << bit)) != 0) { ca.data[jj] ^= ca.data[j]; ccb[jj].xor(ccb[j]); } } } for (int j = 0; j < cn; j++) { if (cans.get(j)) { ans[ccl.data[j]] = true; ++ansN; } } int nz = 0; for (int j = 0; j < cn; j++) { if (ca.data[j] == 0) { ++nz; } } nZeros[i] = nz; bitZeros[i] = new BitSet[nz]; nz = 0; for (int j = 0; j < cn; j++) { if (ca.data[j] == 0) { bitZeros[i][nz++] = ccb[j]; } } } } int idx[] = new int[q]; for (int i = 0; i < q; i++) { idx[i] = i; } sortBy(idx, q, nZeros); Random rng = new Random(42); while (ansN != n) { for (int i = q - 1; i >= 0; i--) { int ii = idx[i]; if (nZeros[ii] == 0) { break; } IntList ccl = cls[ii]; int cn = ccl.size; int j = rng.nextInt(nZeros[ii]); if (lzeros[ii] != null) { long z = lzeros[ii][j]; for (int k = 0; k < cn; k++) { if ((z & (1L << k)) != 0) { ansN += (ans[ccl.data[k]] ^= true) ? 1 : -1; } } } else { BitSet z = bitZeros[ii][j]; for (int k = 0; k < cn; k++) { if (z.get(k)) { ansN += (ans[ccl.data[k]] ^= true) ? 1 : -1; } } } if (ansN == n) { break; } } } for (int i = 1; i <= c; i++) { if (ans[i]) { out.print(i + " "); } } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Alice gave Bob two integers a and b (a > 0 and b β‰₯ 0). Being a curious boy, Bob wrote down an array of non-negative integers with \operatorname{MEX} value of all elements equal to a and \operatorname{XOR} value of all elements equal to b. What is the shortest possible length of the array Bob wrote? Recall that the \operatorname{MEX} (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the \operatorname{XOR} of an array is the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all the elements of the array. Input The input consists of multiple test cases. The first line contains an integer t (1 ≀ t ≀ 5 β‹… 10^4) β€” the number of test cases. The description of the test cases follows. The only line of each test case contains two integers a and b (1 ≀ a ≀ 3 β‹… 10^5; 0 ≀ b ≀ 3 β‹… 10^5) β€” the \operatorname{MEX} and \operatorname{XOR} of the array, respectively. Output For each test case, output one (positive) integer β€” the length of the shortest array with \operatorname{MEX} a and \operatorname{XOR} b. We can show that such an array always exists. Example Input 5 1 1 2 1 2 0 1 10000 2 10000 Output 3 2 3 2 3 Note In the first test case, one of the shortest arrays with \operatorname{MEX} 1 and \operatorname{XOR} 1 is [0, 2020, 2021]. In the second test case, one of the shortest arrays with \operatorname{MEX} 2 and \operatorname{XOR} 1 is [0, 1]. It can be shown that these arrays are the shortest arrays possible.
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 15; const int mod = 1e9 + 7; inline int read() { int ret = 0, op = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') op = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { ret = ret * 10 + ch - '0'; ch = getchar(); } return ret * op; } inline long long readll() { long long ret = 0, op = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') op = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { ret = ret * 10 + ch - '0'; ch = getchar(); } return ret * op; } void write(int x) { if (x < 0) { putchar('-'); x = -x; } if (x >= 10) write(x / 10); putchar(x % 10 + '0'); } inline int Max(const int e, const int f) { return e > f ? e : f; } int xr[N]; int main() { for (register int i = 1; i <= 3e5; i++) xr[i] = xr[i - 1] ^ i; int t = read(); while (t--) { int a = read(); int b = read(); if (xr[a - 1] == b) printf("%d\n", a); else { if ((xr[a - 1] ^ b) == a) { printf("%d\n", a + 2); } else printf("%d\n", a + 1); } } return 0; }
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully β€” instead of carrying to the next column, she carries to the column two columns to the left. For example, the regular way to evaluate the sum 2039 + 2976 would be as shown: <image> However, Alice evaluates it as shown: <image> In particular, this is what she does: * add 9 and 6 to make 15, and carry the 1 to the column two columns to the left, i. e. to the column "0 9"; * add 3 and 7 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column "2 2"; * add 1, 0, and 9 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column above the plus sign; * add 1, 2 and 2 to make 5; * add 1 to make 1. Thus, she ends up with the incorrect result of 15005. Alice comes up to Bob and says that she has added two numbers to get a result of n. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of n. Note that pairs (a, b) and (b, a) are considered different if a β‰  b. Input The input consists of multiple test cases. The first line contains an integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The description of the test cases follows. The only line of each test case contains an integer n (2 ≀ n ≀ 10^9) β€” the number Alice shows Bob. Output For each test case, output one integer β€” the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of n. Example Input 5 100 12 8 2021 10000 Output 9 4 7 44 99 Note In the first test case, when Alice evaluates any of the sums 1 + 9, 2 + 8, 3 + 7, 4 + 6, 5 + 5, 6 + 4, 7 + 3, 8 + 2, or 9 + 1, she will get a result of 100. The picture below shows how Alice evaluates 6 + 4: <image>
#include <bits/stdc++.h> using namespace std; const long long N = 300010, M = 11, Mod = 1e9 + 7; long long n, m, a[N]; long long Dp[M][2][2]; string s; long long Solve(int i = 0, int Cur = 0, int Nxt = 0) { if (i == n) { return (Cur == 0 && Nxt == 0); } long long &Res = Dp[i][Cur][Nxt]; if (Res != -1) { return Res; } Res = 0; for (int j = 0; j <= 9; j++) { for (int k = 0; k <= 9; k++) { if (j == k) { continue; } int Need = (s[i] - '0'); int Sum = (Cur + j + k); int Rem = (Sum % 10); int Cary = (Sum >= 10); if (Rem == Need) { Res += Solve(i + 1, Nxt, Cary); } } } for (int j = 0; j <= 9; j++) { int Need = (s[i] - '0'); int Sum = (Cur + j + j); int Rem = (Sum % 10); int Cary = (Sum >= 10); if (Rem == Need) { Res += Solve(i + 1, Nxt, Cary); } } return Res; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int TT; cin >> TT; for (int T = 1; T <= TT; T++) { cin >> s; reverse(s.begin(), s.end()); n = s.size(); memset(Dp, -1, sizeof Dp); long long Ans = Solve(); cout << Ans - 2 << endl; } return 0; }
On the board, Bob wrote n positive integers in [base](https://en.wikipedia.org/wiki/Positional_notation#Base_of_the_numeral_system) 10 with sum s (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-11 integers and adds them up (in base 11). What numbers should Bob write on the board, so Alice's sum is as large as possible? Input The input consists of multiple test cases. The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases. The description of the test cases follows. The only line of each test case contains two integers s and n (1 ≀ s ≀ 10^9; 1 ≀ n ≀ min(100, s)) β€” the sum and amount of numbers on the board, respectively. Numbers s and n are given in decimal notation (base 10). Output For each test case, output n positive integers β€” the numbers Bob should write on the board, so Alice's sum is as large as possible. If there are multiple answers, print any of them. Example Input 6 97 2 17 1 111 4 100 2 10 9 999999 3 Output 70 27 17 3 4 100 4 10 90 1 1 2 1 1 1 1 1 1 999900 90 9 Note In the first test case, 70_{10} + 27_{10} = 97_{10}, and Alice's sum is $$$70_{11} + 27_{11} = 97_{11} = 9 β‹… 11 + 7 = 106_{10}. (Here x_b represents the number x in base b.) It can be shown that it is impossible for Alice to get a larger sum than 106_{10}$$$. In the second test case, Bob can only write a single number on the board, so he must write 17. In the third test case, 3_{10} + 4_{10} + 100_{10} + 4_{10} = 111_{10}, and Alice's sum is $$$3_{11} + 4_{11} + 100_{11} + 4_{11} = 110_{11} = 1 β‹… 11^2 + 1 β‹… 11 = 132_{10}. It can be shown that it is impossible for Alice to get a larger sum than 132_{10}$$$.
#include <bits/stdc++.h> using namespace std; int main() { int tests; cin >> tests; while (tests--) { int sum, elements; cin >> sum >> elements; int aux_sum = sum, digit_sum = 0; while (aux_sum) { digit_sum += aux_sum % 10; aux_sum /= 10; } int power = 1; if (elements <= digit_sum) { vector<int> dividing; dividing.push_back(sum); while (dividing.size() < elements) { while (dividing[0] / power % 10 == 0) { power *= 10; } while (dividing.size() < elements and dividing[0] / power % 10 > 0) { dividing.push_back(power); dividing[0] -= power; } } for (int nr : dividing) { cout << nr << ' '; } cout << '\n'; } else { multiset<int> dividing; int act_elements = 1; while (sum / power > 1) { while (sum / power % 10 == 0) { power *= 10; } while (sum / power % 10 > 0 and sum / power > 1) { dividing.insert(power); act_elements++; sum -= power; } } dividing.insert(sum); while (act_elements < elements) { int nr = *dividing.begin(); dividing.erase(dividing.begin()); if (nr == 1) { continue; } power = 1; while (nr > power * 10) { power *= 10; } dividing.insert(power); nr -= power; while (nr > 0 and act_elements < elements) { if (act_elements == elements - 1) { dividing.insert(nr); act_elements++; } else { dividing.insert(power); nr -= power; act_elements++; } } } for (int nr : dividing) { cout << nr << ' '; } for (int i = 1; i <= elements - dividing.size(); ++i) { cout << 1 << ' '; } cout << '\n'; } } return 0; }
Alice has recently received an array a_1, a_2, ..., a_n for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too! However, soon Bob became curious, and as any sane friend would do, asked Alice to perform q operations of two types on her array: * 1 x y: update the element a_x to y (set a_x = y). * 2 l r: calculate how many non-decreasing subarrays exist within the subarray [a_l, a_{l+1}, ..., a_r]. More formally, count the number of pairs of integers (p,q) such that l ≀ p ≀ q ≀ r and a_p ≀ a_{p+1} ≀ ... ≀ a_{q-1} ≀ a_q. Help Alice answer Bob's queries! Input The first line contains two integers n and q (1 ≀ n, q ≀ 2 β‹… 10^5) β€” the size of the array, and the number of queries, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) β€” the elements of Alice's array. The next q lines consist of three integers each. The first integer of the i-th line is t_i, the operation being performed on the i-th step (t_i = 1 or t_i = 2). If t_i = 1, the next two integers are x_i and y_i (1 ≀ x_i ≀ n; 1 ≀ y_i ≀ 10^9), updating the element at position x_i to y_i (setting a_{x_i} = y_i). If t_i = 2, the next two integers are l_i and r_i (1 ≀ l_i ≀ r_i ≀ n), the two indices Bob asks Alice about for the i-th query. It's guaranteed that there is at least one operation of the second type. Output For each query of type 2, print a single integer, the answer to the query. Example Input 5 6 3 1 4 1 5 2 2 5 2 1 3 1 4 4 2 2 5 1 2 6 2 2 5 Output 6 4 10 7 Note For the first query, l = 2 and r = 5, and the non-decreasing subarrays [p,q] are [2,2], [3,3], [4,4], [5,5], [2,3] and [4,5].
#include <bits/stdc++.h> using namespace std; long long s[2000500], sum[2000500]; void add(int l, int r, int nl, int nr, int cur, long long ad) { if (l == nl && r == nr) { sum[cur] = (sum[cur] + ad); s[cur] = (s[cur] + ad * (r - l + 1)); if (l != r && sum[cur]) { sum[(cur << 1)] = (sum[(cur << 1)] + sum[cur]); s[(cur << 1)] = (s[(cur << 1)] + sum[cur] * (((l + r) >> 1) - l + 1)); sum[((cur << 1) + 1)] = (sum[((cur << 1) + 1)] + sum[cur]); s[((cur << 1) + 1)] = (s[((cur << 1) + 1)] + sum[cur] * (r - ((l + r) >> 1))); sum[cur] = 0; }; return; } if (l != r && sum[cur]) { sum[(cur << 1)] = (sum[(cur << 1)] + sum[cur]); s[(cur << 1)] = (s[(cur << 1)] + sum[cur] * (((l + r) >> 1) - l + 1)); sum[((cur << 1) + 1)] = (sum[((cur << 1) + 1)] + sum[cur]); s[((cur << 1) + 1)] = (s[((cur << 1) + 1)] + sum[cur] * (r - ((l + r) >> 1))); sum[cur] = 0; }; if (nr <= ((l + r) >> 1)) { add(l, ((l + r) >> 1), nl, nr, (cur << 1), ad); } else { if (nl > ((l + r) >> 1)) { add(((l + r) >> 1) + 1, r, nl, nr, ((cur << 1) + 1), ad); } else { add(l, ((l + r) >> 1), nl, ((l + r) >> 1), (cur << 1), ad); add(((l + r) >> 1) + 1, r, ((l + r) >> 1) + 1, nr, ((cur << 1) + 1), ad); } } s[cur] = (s[(cur << 1)] + s[((cur << 1) + 1)]); } long long ask(int l, int r, int nl, int nr, int cur) { if (l != r && sum[cur]) { sum[(cur << 1)] = (sum[(cur << 1)] + sum[cur]); s[(cur << 1)] = (s[(cur << 1)] + sum[cur] * (((l + r) >> 1) - l + 1)); sum[((cur << 1) + 1)] = (sum[((cur << 1) + 1)] + sum[cur]); s[((cur << 1) + 1)] = (s[((cur << 1) + 1)] + sum[cur] * (r - ((l + r) >> 1))); sum[cur] = 0; }; if (l == nl && r == nr) { return s[cur]; } if (nr <= ((l + r) >> 1)) { return ask(l, ((l + r) >> 1), nl, nr, (cur << 1)); } if (nl > ((l + r) >> 1)) { return ask(((l + r) >> 1) + 1, r, nl, nr, ((cur << 1) + 1)); } return ask(l, ((l + r) >> 1), nl, ((l + r) >> 1), (cur << 1)) + ask(((l + r) >> 1) + 1, r, ((l + r) >> 1) + 1, nr, ((cur << 1) + 1)); } int i, j, k, l, r, n, m, t, a[200500], sb, tmp; set<int> st; int main() { scanf("%d%d", &n, &t); for (i = 1; i <= n; i++) { scanf("%d", &a[i]); } st.insert(n + 1); st.insert(1); st.insert(0); for (i = 1; i <= n; i++) { if (a[i] >= a[i - 1]) { k++; } else { k = 1; st.insert(i); } add(1, n, i, i, 1, k); } while (t--) { scanf("%d", &sb); if (sb == 1) { scanf("%d%d", &j, &k); auto it = st.upper_bound(j); r = *it - 1; it--; l = *it; a[j] = k; if (j == 1) { goto aaa; } if (a[j - 1] <= a[j]) { if (l == j) { tmp = ask(1, n, j - 1, j - 1, 1); add(1, n, j, r, 1, tmp); st.erase(l); } } else { if (l != j) { tmp = ask(1, n, j - 1, j - 1, 1); add(1, n, j, r, 1, -tmp); st.insert(j); } } aaa:; if (j == n) { goto bbb; } it = st.upper_bound(j); r = *it - 1; it--; l = *it; if (a[j] <= a[j + 1]) { if (r == j) { tmp = ask(1, n, j, j, 1); add(1, n, j + 1, *st.upper_bound(j + 1) - 1, 1, tmp); st.erase(j + 1); } } else { if (r != j) { tmp = ask(1, n, j, j, 1); add(1, n, j + 1, r, 1, -tmp); st.insert(j + 1); } } bbb:; } else { scanf("%d%d", &j, &k); auto it = st.upper_bound(k); it--; if (*it <= j) { long long sb = k - j + 1; printf("%lld\n", sb * (sb + 1) / 2); continue; } r = *it; it = st.lower_bound(j); l = *it; long long ans = ask(1, n, j, k, 1); if (l > j) { ans -= ask(1, n, j, l - 1, 1); long long sb = l - j; ans += (sb * sb + sb) / 2; } printf("%lld\n", ans); } } }
Alice has an empty grid with n rows and m columns. Some of the cells are marked, and no marked cells are adjacent to the edge of the grid. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: * every unmarked cell contains either the number 1 or 4; * every marked cell contains the sum of the numbers in all unmarked cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is 0); * every marked cell contains a multiple of 5. Alice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 500) β€” the number of rows and the number of columns in the grid, respectively. Then n lines follow, each containing m characters. Each of these characters is either '.' or 'X' β€” an unmarked and a marked cell, respectively. No marked cells are adjacent to the edge of the grid. Output Output "'NO" if no suitable grid exists. Otherwise, output "'YES"'. Then output n lines of m space-separated integers β€” the integers in the grid. Examples Input 5 5 ..... .XXX. .X.X. .XXX. ..... Output YES 4 1 4 4 1 4 5 5 5 1 4 5 1 5 4 1 5 5 5 4 1 4 4 1 4 Input 5 5 ..... .XXX. .XXX. .XXX. ..... Output NO Input 3 2 .. .. .. Output YES 4 1 4 1 1 4 Input 9 9 ......... .XXXXX.X. .X...X... .X.XXXXX. .X.X.X.X. .X.XXX.X. .X.....X. .XXXXXXX. ......... Output YES 4 4 4 1 4 1 4 1 4 1 5 5 5 5 5 4 10 1 4 5 1 4 1 5 4 4 4 4 5 1 5 5 0 5 5 1 4 5 1 5 4 5 1 5 4 4 5 1 5 5 5 4 5 1 1 5 4 4 1 1 4 5 1 4 5 5 5 5 5 5 5 4 1 1 1 1 4 4 1 1 4 Note It can be shown that no such grid exists for the second test.
#include <bits/stdc++.h> using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; const int N = 505; char c[N][N]; int comp[N][N]; int countComp = 0; int color[N * N]; int res[N][N]; int n, m; vector<int> adj[N * N]; inline bool inside(int u, int v) { return 0 < u && u <= n && 0 < v && v <= m; } void DFS(int u, int v) { comp[u][v] = countComp; for (int x = u - 1; x <= u + 1; ++x) { for (int y = v - 1; y <= v + 1; ++y) { if (!inside(x, y) || c[x][y] != '.' || comp[x][y] > 0) continue; DFS(x, y); } } } void colorDFS(int u, int val) { color[u] = val; for (auto v : adj[u]) { if (color[v] > 0) { if (color[u] == color[v]) { cout << "NO\n"; exit(0); } continue; } colorDFS(v, val ^ 3); } } int main() { srand(time(NULL)); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> c[i][j]; } } countComp = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (c[i][j] == 'X' || comp[i][j] > 0) continue; ++countComp; DFS(i, j); } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (c[i][j] != 'X') continue; int cnt = 0; for (int k = 0; k < 4; ++k) { cnt += (inside(i + dx[k], j + dy[k]) && c[i + dx[k]][j + dy[k]] == '.'); } if (cnt & 1) { cout << "NO\n"; exit(0); } if (j > 0 && c[i][j - 1] == '.' && j < m && c[i][j + 1] == '.' && comp[i][j - 1] != comp[i][j + 1]) { adj[comp[i][j - 1]].emplace_back(comp[i][j + 1]); adj[comp[i][j + 1]].emplace_back(comp[i][j - 1]); } if (i > 0 && c[i - 1][j] == '.' && i < n && c[i + 1][j] == '.' && comp[i + 1][j] != comp[i - 1][j]) { adj[comp[i + 1][j]].emplace_back(comp[i - 1][j]); adj[comp[i - 1][j]].emplace_back(comp[i + 1][j]); } } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (color[comp[i][j]] > 0) continue; colorDFS(comp[i][j], 1); } } for (int j = 1; j <= m; ++j) { int val = ((j & 1) ? 1 : 4); res[1][j] = val; int pre = color[comp[1][j]]; for (int i = 2; i <= n; ++i) { if (c[i][j] == 'X') continue; if (pre != color[comp[i][j]]) { val = (val == 1 ? 4 : 1); } res[i][j] = val; pre = color[comp[i][j]]; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (c[i][j] != 'X') continue; for (int k = 0; k < 4; ++k) { int u = i + dx[k]; int v = j + dy[k]; if (!inside(u, v) || c[u][v] == 'X') continue; res[i][j] += res[u][v]; } } } cout << "YES\n"; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cout << res[i][j] << " \n"[j == m]; } } }
You are given a string s, consisting of n letters, each letter is either 'a' or 'b'. The letters in the string are numbered from 1 to n. s[l; r] is a continuous substring of letters from index l to r of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings "baba" and "aabbab" are balanced and strings "aaab" and "b" are not. Find any non-empty balanced substring s[l; r] of string s. Print its l and r (1 ≀ l ≀ r ≀ n). If there is no such substring, then print -1 -1. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of the testcase contains a single integer n (1 ≀ n ≀ 50) β€” the length of the string. The second line of the testcase contains a string s, consisting of n letters, each letter is either 'a' or 'b'. Output For each testcase print two integers. If there exists a non-empty balanced substring s[l; r], then print l r (1 ≀ l ≀ r ≀ n). Otherwise, print -1 -1. Example Input 4 1 a 6 abbaba 6 abbaba 9 babbabbaa Output -1 -1 1 6 3 6 2 5 Note In the first testcase there are no non-empty balanced subtrings. In the second and third testcases there are multiple balanced substrings, including the entire string "abbaba" and substring "baba".
for _ in range (int(input())): n=int(input()) s=input() p=0 if("a" in s): p+=1 if("b" in s): p+=1 if(p<2): print("-1 -1") else: if("ab" in s): z=s.index("ab") print(str(z+1)+" "+str(z+2)) else: z=s.index("ba") print(str(z+1)+" "+str(z+2))
A chess tournament will be held soon, where n chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players. Each of the players has their own expectations about the tournament, they can be one of two types: 1. a player wants not to lose any game (i. e. finish the tournament with zero losses); 2. a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible. Input The first line contains a single integer t (1 ≀ t ≀ 200) β€” the number of test cases. The first line of each test case contains one integer n (2 ≀ n ≀ 50) β€” the number of chess players. The second line contains the string s (|s| = n; s_i ∈ \{1, 2\}). If s_i = 1, then the i-th player has expectations of the first type, otherwise of the second type. Output For each test case, print the answer in the following format: In the first line, print NO if it is impossible to meet the expectations of all players. Otherwise, print YES, and the matrix of size n Γ— n in the next n lines. The matrix element in the i-th row and j-th column should be equal to: * +, if the i-th player won in a game against the j-th player; * -, if the i-th player lost in a game against the j-th player; * =, if the i-th and j-th players' game resulted in a draw; * X, if i = j. Example Input 3 3 111 2 21 4 2122 Output YES X== =X= ==X NO YES X--+ +X++ +-X- --+X
from collections import Counter, defaultdict from sys import stdin,stdout import io , os , sys #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline input = stdin.readline def mapinput(): return map(int, input().split()) def listinput(): return list( map( int, input().split())) def intinput(): return int(stdin.readline()) def strinput(): return input().strip() def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False ans = [] for p in range(n + 1): if prime[p]: ans.append(p) return ans def writ(ss): stdout.write(str(ss) + "\n") for test in range(int(input())): def solve(): n = intinput() s = strinput() cc = Counter(s) #print(cc) if cc['2'] == 1 or cc['2'] == 2: print("NO") return ans = [["X"] * n for i in range(n) ] for i in range(n): flag = 0 for j in range(i+1 , n): if s[i] == '1' or s[j] == '1': ans[i][j] = "=" ans[j][i] = '=' else: if flag == 0: ans[i][j] = "+" ans[j][i] = "-" flag = 1 else: ans[i][j] = "-" ans[j][i] = "+" print("YES") for i in range(n): print(''.join(ans[i])) solve()
n people gathered to hold a jury meeting of the upcoming competition, the i-th member of the jury came up with a_i tasks, which they want to share with each other. First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation p of numbers from 1 to n (an array of size n where each integer from 1 to n occurs exactly once). Then the discussion goes as follows: * If a jury member p_1 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. * If a jury member p_2 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. * ... * If a jury member p_n has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. * If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation p is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo 998 244 353. Input The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. The first line of the test case contains a single integer n (2 ≀ n ≀ 2 β‹… 10^5) β€” number of jury members. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9) β€” the number of problems that the i-th member of the jury came up with. The sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, print one integer β€” the number of nice permutations, taken modulo 998 244 353. Example Input 4 2 1 2 3 5 5 5 4 1 3 3 7 6 3 4 2 1 3 3 Output 1 6 0 540 Note Explanation of the first test case from the example: There are two possible permutations, p = [1, 2] and p = [2, 1]. For p = [1, 2], the process is the following: 1. the first jury member tells a task; 2. the second jury member tells a task; 3. the first jury member doesn't have any tasks left to tell, so they are skipped; 4. the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice. For p = [2, 1], the process is the following: 1. the second jury member tells a task; 2. the first jury member tells a task; 3. the second jury member tells a task. So, this permutation is nice.
#include <bits/stdc++.h> using namespace std; int a[1111111]; int q; int n; int64_t gt[1111111]; int64_t Powe(int a, int n) { if (n == 0) return 1; if (n == 1) return a; int64_t b = Powe(a, n / 2); b = (b * b) % 998244353; if (n % 2 == 1) return (b * a) % 998244353; else return b; } int main() { scanf("%d", &q); gt[0] = 1; for (int i = 1; i <= 1000000; i++) gt[i] = (gt[i - 1] * i) % 998244353; for (int z = 1; z <= q; z++) { scanf("%d", &n); int an, as = 0; bool ok = true; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (as < a[i]) { an = as; as = a[i]; } else an = max(an, a[i]); } sort(a + 1, a + n + 1); int A = upper_bound(a + 1, a + n + 1, a[n]) - lower_bound(a + 1, a + n + 1, a[n]); if (A > 1) { cout << gt[n] << endl; ok = false; } if (a[n] - an > 1) { cout << 0 << endl; ok = false; } if (ok) { int B = upper_bound(a + 1, a + n + 1, an) - lower_bound(a + 1, a + n + 1, an); int64_t dd = (gt[B] * gt[n - B - 1]) % 998244353; int T = n - B - 1; int64_t X = 1; for (int i = B + 2; i <= n; i++) { int u = i - B - 1; int64_t cc = (gt[u] * gt[T - u]) % 998244353; cc = (gt[T] * Powe(cc, 998244353 - 2)) % 998244353; dd = (dd + (((gt[i - 1] * cc) % 998244353) * gt[n - i]) % 998244353) % 998244353; } cout << (gt[n] - dd + 998244353) % 998244353 << endl; } } }