input
stringlengths 29
13k
| output
stringlengths 9
73.4k
|
---|---|
Alice and Bob always had hard time choosing restaurant for the dinner. Previously they performed Eenie Meenie Miney Mo game, but eventually as their restaurant list grew, they had to create a new game. This new game starts as they write restaurant names on N cards and align the cards in one line. Before the game begins, they both choose starting card and starting direction they are going to. They take turns in order one after another. After each turn, they move one card in their current direction. If they reach the end or beginning of the line of cards they change direction. Once they meet in a card, the card is marked for removal and is removed the first moment they both leave the card.
<image> Example of how card is removed
They repeat this process until there is only one restaurant card left. Since there are a lot of restaurant cards, they are bored to simulate this process over and over and need your help to determine the last card that remains. Can you help them?
Input
The first line of the input is one integer T (1 ≤ T ≤ 10^{4}) representing number of test cases. Each test case contains 3 lines: The first line contains an integer N representing initial number of cards. Next line contains two integer values A,B (0 ≤ A, B < N, 2 ≤ N ≤ 10^{18}) representing starting 0-based index of the card in the array. Last line contains two strings D_A, D_B ∈ {"left", "right"} representing starting direction of their movement.
Output
The output contains T integer number – the 0-based index of the last card that remains for every test case in order.
Example
Input
1
4
0 1
left right
Output
0
Note
Note that since Alice is starting at the beginning of the line even though her initial direction is left, on her next move she will go right. | #include <bits/stdc++.h>
using namespace std;
long long w, n, a, b, da, db;
string s, s2;
bool jo;
void v0() {
if (!jo) {
cout << 0 << "\n";
jo = 1;
}
}
void v1() {
if (!jo) {
cout << n - 1 << "\n";
jo = 1;
}
}
void valt() {
if (a == 1 && da == -1 || a == n && da == 1) {
da *= -1;
}
if (b == 1 && db == -1 || b == n && db == 1) {
db *= -1;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin >> w;
while (w--) {
cin >> n >> a >> b;
a++, b++;
cin >> s >> s2;
da = (s == "left" ? -1 : 1);
db = (s2 == "left" ? -1 : 1);
valt();
if (a + da == b) {
a = b;
swap(da, db);
}
if (a != b) {
while (da == db || a < b && da == -1 || b < a && db == -1) {
long long ta = (da == 1 ? n - a : a - 1),
tb = (db == 1 ? n - b : b - 1), lep = min(ta, tb);
a += lep * da, b += lep * db;
valt();
}
long long koz = (a + b) / 2;
if ((a + b) % 2 && a < b) {
koz++;
}
if ((a + b) % 2) {
swap(da, db);
}
a = b = koz;
}
valt();
if (a == 1) v1();
if (a == n) v0();
if (da == db) {
if (da == 1)
v0();
else
v1();
}
if (da == -1)
v0();
else
v1();
jo = 0;
}
return 0;
}
|
Little Johnny Bubbles enjoys spending hours in front of his computer playing video games. His favorite game is Bubble Strike, fast-paced bubble shooting online game for two players.
Each game is set in one of the N maps, each having different terrain configuration. First phase of each game decides on which map the game will be played. The game system randomly selects three maps and shows them to the players. Each player must pick one of those three maps to be discarded. The game system then randomly selects one of the maps that were not picked by any of the players and starts the game.
Johnny is deeply enthusiastic about the game and wants to spend some time studying maps, thus increasing chances to win games played on those maps. However, he also needs to do his homework, so he does not have time to study all the maps. That is why he asked himself the following question: "What is the minimum number of maps I have to study, so that the probability to play one of those maps is at least P"?
Can you help Johnny find the answer for this question? You can assume Johnny's opponents do not know him, and they will randomly pick maps.
Input
The first line contains two integers N (3 ≤ N ≤ 10^{3}) and P (0 ≤ P ≤ 1) – total number of maps in the game and probability to play map Johnny has studied. P will have at most four digits after the decimal point.
Output
Output contains one integer number – minimum number of maps Johnny has to study.
Example
Input
7 1.0000
Output
6 | #include <bits/stdc++.h>
using namespace std;
int main() {
int N;
float P;
cin >> N >> P;
for (int k = 0; k <= N; k++) {
float c0 = (N - k) * (N - k - 1) * (N - k - 2) / 6.0;
float c1 = k * ((N - k) * (N - k - 1)) / 2.0;
float c2 = k * (k - 1) / 2 * (N - k) / 1.0;
float c3 = k * (k - 1) * (k - 2) / 6.0;
float p = (0 + 0.5 * c1 + c2 + c3) / (c0 + c1 + c2 + c3);
if ((p - P) >= 0) {
cout << k << endl;
break;
}
}
return 0;
}
|
There are N bubbles in a coordinate plane. Bubbles are so tiny that it can be assumed that each bubble is a point (X_i, Y_i).
Q Bubble Cup finalists plan to play with the bubbles. Each finalist would link to use infinitely long Bubble Cup stick to pop some bubbles. The i-th finalist would like to place the stick in the direction of vector (dxi, dyi), and plays the following game until K_i bubbles are popped. The game starts with finalist placing the stick in the direction of vector (dx_i, dy_i), and sweeping it from the infinity to the left until it hits some bubble, which is immediately popped. It is guaranteed that only one bubble will be hit in this step. After that the finalist starts rotating the stick in the counter clockwise direction with the center of rotation in point where the previous bubble was popped. When the next bubble is hit, it is immediately popped and becomes the new center of rotation. The process continues until K_i bubbles have been popped. It is guaranteed that the stick won't hit two bubbles simultaneously in this process.
For each finalist find which bubble would be popped the last. Note that each game starts with the configuration of all N bubbles, so the games don't depend on the previous games.
Input
The first line contains one integer N — the number of bubbles. (1 ≤ N ≤ 10^5)
Each of the next N lines contains two integers. The i-th line contains integers X_i and Y_i — the coordinates of the i-th bubble. (-10^9 ≤ X_i, Y_i ≤ 10^9, (X_i, Y_i) ≠ (X_j, Y_j) for i ≠ j)
The next line contains one integer Q — the number of finalists willing to play with the bubbles. (1 ≤ Q ≤ 10^5)
Each of the next Q lines contains 3 integers. The i-th line contains integers dx_i, dy_i and K_i. (-10^9 ≤ dx_i, dy_i ≤ 10^9, 1 ≤ K_i ≤ N)
Output
For each of the Q finalists, print the index of the bubble which would be popped last, in the separate line.
Examples
Input
4
0 0
1 0
0 1
1 1
2
1 -1 3
-1 1 4
Output
4
2
Input
4
1 1
2 2
7 1
1 7
3
2 2 1
1 -5 4
-6 5 3
Output
3
2
3
Note
There are two finalists willing to play with the bubbles. If the first finalist plays with the bubbles, then the bubbles at coordinates (0, 0), (1, 0) and (1, 1) would be popped in that order. Their indexes are 1, 2 and 4, so the answer is 4. If the second finalist plays with the bubbles, then the bubbles at coordinates (1, 1), (0, 1), (0, 0) and (1, 0) would be popped in that order, so the answer is 2.
Visualization: [link](https://petljamediastorage.blob.core.windows.net/uploads/example1.gif). | #include <bits/stdc++.h>
using namespace std;
using Point = complex<int>;
using ll = long long;
ll cross(Point a, Point b) {
return 1LL * a.real() * b.imag() - 1LL * b.real() * a.imag();
}
ll det(Point a, Point b, Point c) { return cross(b - a, c - a); }
namespace std {
bool operator<(const Point& a, const Point& b) {
return make_pair(a.real(), a.imag()) < make_pair(b.real(), b.imag());
}
} // namespace std
struct DynHull {
struct Node {
int bl, br, l, r, lc, rc;
};
vector<Node> T = {{-1, -1, -1, -1, 0, 0}};
vector<Point> P;
DynHull(vector<Point> P) : P(P) {}
bool leaf(int x) { return T[x].l == T[x].r; }
int combine(int lc, int rc, int ret = -1) {
if (!lc || !rc) return lc + rc;
if (ret == -1 || ret == lc || ret == rc) ret = T.size(), T.push_back({});
T[ret] = {-1, -1, T[lc].l, T[rc].r, lc, rc};
while (!leaf(lc) || !leaf(rc)) {
int a = T[lc].bl, b = T[lc].br, c = T[rc].bl, d = T[rc].br;
if (a != b && det(P[a], P[b], P[c]) > 0) {
lc = T[lc].lc;
} else if (c != d && det(P[b], P[c], P[d]) > 0) {
rc = T[rc].rc;
} else if (a == b) {
rc = T[rc].lc;
} else if (c == d) {
lc = T[lc].rc;
} else {
auto s1 = det(P[a], P[b], P[c]), s2 = det(P[a], P[b], P[d]);
assert(s1 >= s2);
auto xc = P[c].real(), xd = P[d].real(), xm = P[T[rc].l].real();
if (s1 == s2 || s1 * xd - s2 * xc < (s1 - s2) * xm) {
lc = T[lc].rc;
} else {
rc = T[rc].lc;
}
}
}
T[ret].bl = T[lc].l;
T[ret].br = T[rc].l;
return ret;
}
int Build(int b, int e) {
if (e - b == 1) {
T.push_back({b, b, b, b, 0, 0});
return T.size() - 1;
}
int m = (b + e) / 2;
return combine(Build(b, m), Build(m, e));
}
int Erase(int x, int pos) {
if (!x || T[x].r < pos || T[x].l > pos) return x;
return leaf(x) ? 0 : combine(Erase(T[x].lc, pos), Erase(T[x].rc, pos), x);
}
template <typename Callback>
void Hull(int x, Callback&& cb, int l = 0, int r = 1e9) {
if (!x || l > r) return;
if (leaf(x)) {
cb(T[x].l);
return;
}
Hull(T[x].lc, cb, l, min(r, T[x].bl));
Hull(T[x].rc, cb, max(l, T[x].br), r);
}
};
inline ll area(Point a, Point b, Point c) {
return (ll)(b.real() - a.real()) * (c.imag() - a.imag()) -
(ll)(b.imag() - a.imag()) * (c.real() - a.real());
}
vector<Point> convexHull(vector<Point> p) {
int n = p.size(), m = 0;
if (n < 3) return p;
vector<Point> hull(n + n);
sort(p.begin(), p.end());
for (int i = 0; i < n; ++i) {
while (m > 1 and area(hull[m - 2], hull[m - 1], p[i]) <= 0) --m;
hull[m++] = p[i];
}
for (int i = n - 2, j = m + 1; i >= 0; --i) {
while (m >= j and area(hull[m - 2], hull[m - 1], p[i]) <= 0) --m;
hull[m++] = p[i];
}
hull.resize(m - 1);
return hull;
}
const int LG = 18;
const int N = 100010;
int q, par[LG][N];
inline int prv(int i, int n) { return (i ? i : n) - 1; }
inline int nxt(int i, int n) { return i + 1 < n ? i + 1 : 0; }
int kthPar(int u, int k) {
for (int i = LG - 1; i >= 0; --i) {
assert(u != -1);
if (k & 1 << i) k ^= 1 << i, u = par[i][u];
}
return u;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<pair<Point, int>> pts(n);
map<Point, int> id;
for (int i = 0; i < n; ++i) {
int x, y;
cin >> x >> y;
pts[i] = make_pair(Point{x, y}, i);
id[Point{x, y}] = i;
}
if (n == 1) {
cin >> q;
while (q--) cout << 1 << '\n';
return 0;
}
vector<pair<Point, int>> pts_copy = pts;
sort(pts.begin(), pts.end());
vector<Point> P(n);
vector<int> remap(n);
for (int i = 0; i < n; ++i) {
remap[i] = pts[i].second;
P[i] = pts[i].first;
}
auto LH = DynHull(P);
int lh = LH.Build(0, n);
for (int i = 0; i < n; ++i) P[i] = -P[i];
reverse(P.begin(), P.end());
auto UH = DynHull(P);
int uh = UH.Build(0, n);
vector<int> layer(n, -1);
for (int i = 0;; ++i) {
vector<int> all;
LH.Hull(lh, [&](int x) { all.push_back(x); });
UH.Hull(uh, [&](int x) { all.push_back(n - x - 1); });
if (all.empty()) break;
for (auto x : all) {
lh = LH.Erase(lh, x);
uh = UH.Erase(uh, n - x - 1);
layer[remap[x]] = i;
}
}
int up = *max_element(layer.begin(), layer.end()) + 1;
vector<vector<Point>> layers(up);
for (int i = 0; i < n; ++i) {
layers[layer[i]].emplace_back(pts_copy[i].first);
}
for (int i = 0; i < up; ++i) layers[i] = convexHull(layers[i]);
vector<int> pf(up);
for (int i = 0; i < up; ++i) {
pf[i] = layers[i].size();
if (i) pf[i] += pf[i - 1];
}
vector<int> whichLayer(n), whichPos(n);
for (int i = 0; i < up; ++i) {
for (int j = 0; j < layers[i].size(); ++j) {
auto x = layers[i][j];
whichLayer[id[x]] = i, whichPos[id[x]] = j;
}
}
memset(par, -1, sizeof par);
for (int i = 0; i + 1 < up; ++i) {
if (layers[i + 1].size() == 1) {
int to = id[layers[i + 1][0]];
for (auto x : layers[i]) par[0][id[x]] = to;
continue;
}
int k = 0, sz = layers[i + 1].size();
vector<int> to(layers[i].size());
for (int j = 0; j < layers[i].size(); ++j) {
while (area(layers[i][j], layers[i + 1][k], layers[i + 1][nxt(k, sz)]) <
0)
k = nxt(k, sz);
while (area(layers[i][j], layers[i + 1][prv(k, sz)], layers[i + 1][k]) >
0)
k = prv(k, sz);
to[j] = k;
}
for (int j = 0; j < layers[i].size(); ++j) {
int u = id[layers[i][j]],
v = id[layers[i + 1][to[prv(j, layers[i].size())]]];
par[0][u] = v;
}
}
for (auto x : layers[up - 1]) par[0][id[x]] = n;
for (int j = 1; j < LG; ++j) {
for (int i = 0; i <= n; ++i)
if (par[j - 1][i] != -1) {
par[j][i] = par[j - 1][par[j - 1][i]];
}
}
int sz = layers[0].size();
vector<pair<long double, int>> vec;
for (int i = 0; i < sz; ++i) {
Point cur = layers[0][nxt(i, sz)] - layers[0][i];
vec.emplace_back(atan2l(cur.imag(), cur.real()), i);
}
sort(vec.begin(), vec.end());
cin >> q;
while (q--) {
int dx, dy, k;
cin >> dx >> dy >> k;
long double ang = atan2l(dy, dx);
int pos = -1;
auto it = upper_bound(vec.begin(), vec.end(), make_pair(ang, 696969));
if (it == vec.end())
pos = vec[0].second;
else
pos = it->second;
int where = lower_bound(pf.begin(), pf.end(), k) - pf.begin();
int ext = k - (where ? pf[where - 1] : 0);
int at = kthPar(id[layers[0][pos]], where);
assert(at != n);
int final = (whichPos[at] + ext - 1) % (int)layers[where].size();
int ans = id[layers[where][final]];
printf("%d\n", ans + 1);
}
return 0;
}
|
You are given two integer arrays of length N, A1 and A2. You are also given Q queries of 4 types:
1 k l r x: set Ak_i:=min(Ak_i, x) for each l ≤ i ≤ r.
2 k l r x: set Ak_i:=max(Ak_i, x) for each l ≤ i ≤ r.
3 k l r x: set Ak_i:=Ak_i+x for each l ≤ i ≤ r.
4 l r: find the (∑_{i=l}^r F(A1_i+A2_i)) \% (10^9+7) where F(k) is the k-th Fibonacci number (F(0)=0, F(1)=1, F(k)=F(k-1)+F(k-2)), and x \% y denotes the remainder of the division of x by y.
You should process these queries and answer each query of the fourth type.
Input
The first line contains two integers N and Q. (1 ≤ N, Q ≤ 5 × 10^4)
The second line contains N integers, array A1_1, A1_2, ... A1_N. (0 ≤ A1_i ≤ 10^6)
The third line contains N integers, array A2_1, A2_2, ... A2_N. (0 ≤ A2_i ≤ 10^6)
The next Q lines describe the queries. Each line contains 5 or 3 integers, where the first integer denotes the type of the query. (k ∈ \{1, 2\}, 1 ≤ l ≤ r ≤ N)
For queries of type 1 and 2, 0 ≤ x ≤ 10^9 holds.
For queries of type 3, −10^6 ≤ x ≤ 10^6 holds.
It is guaranteed that after every query each number in arrays A1 and A2 will be nonnegative.
Output
Print the answer to each query of the fourth type, in separate lines.
Examples
Input
3 4
1 0 2
2 1 0
4 1 3
3 2 2 2 3
1 1 1 3 0
4 1 3
Output
4
4
Input
5 4
1 3 5 3 2
4 2 1 3 3
4 1 3
4 2 5
2 1 2 4 6
4 2 4
Output
18
26
68
Note
In the first example: The answer for the first query is F(1 + 2) + F(0 + 1) + F(2 + 0) = F(3) + F(1) + F(2) = 2 + 1 + 1 = 4. After the second query, the array A2 changes to [2, 4, 0]. After the third query, the array A1 changes to [0, 0, 0]. The answer for the fourth query is F(0 + 2) + F(0 + 4) + F(0 + 0) = F(2) + F(4) + F(0) = 1 + 3 + 0 = 4.
In the second example: The answer for the first query is F(1 + 4) + F(3 + 2) + F(5 + 1) = F(5) + F(5) + F(6) = 5 + 5 + 8 = 18. The answer for the second query is F(3 + 2) + F(5 + 1) + F(3 + 3) + F(2 + 3) = F(5) + F(6) + F(6) + F(5) = 5 + 8 + 8 + 5 = 26. After the third query, the array A1 changes to [1, 6, 6, 6, 2]. The answer for the fourth query is F(6 + 2) + F(6 + 1) + F(6 + 3) = F(8) + F(7) + F(9) = 21 + 13 + 34 = 68. | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &t) {
t = 0;
char ch = getchar();
int f = 1;
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
do {
(t *= 10) += ch - '0';
ch = getchar();
} while ('0' <= ch && ch <= '9');
t *= f;
}
template <typename T>
void write(T t) {
if (t < 0) {
putchar('-');
write(-t);
return;
}
if (t > 9) write(t / 10);
putchar('0' + t % 10);
}
template <typename T>
void writeln(T t) {
write(t);
puts("");
}
const int maxn = 50005, mod = 1000000007, inv2 = (mod + 1) / 2;
template <typename _Tp1, typename _Tp2>
inline void add(_Tp1 &a, _Tp2 b) {
a = a + b >= mod ? a + b - mod : a + b;
}
template <typename _Tp1, typename _Tp2>
inline void sub(_Tp1 &a, _Tp2 b) {
a = a - b < 0 ? a - b + mod : a - b;
}
long long ksm(long long a, long long b = mod - 2) {
long long res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod, b >>= 1;
}
return res;
}
int n, q;
struct num {
int a, b;
inline num operator+=(const num &o) {
add(a, o.a), add(b, o.b);
return *this;
}
inline num operator+(const num &o) const {
num x(*this);
return x += o;
}
inline num operator-=(const num &o) {
sub(a, o.a), sub(b, o.b);
return *this;
}
inline num operator-(const num &o) const {
num x(*this);
return x -= o;
}
inline num operator*(const num &o) const {
return {(int)((1LL * a * o.a + 5LL * b * o.b) % mod),
(int)((1LL * b * o.a + 1LL * a * o.b) % mod)};
}
inline num operator*(const int &o) const {
return {(int)(1LL * o * a % mod), (int)(1LL * o * b % mod)};
}
inline num inv() const {
long long tmp = ksm((1LL * a * a + 1LL * (mod - 5) * b % mod * b) % mod);
return (num){a, mod - b} * tmp;
}
inline num operator/(const num &o) const { return *this * (o.inv()); }
} w1, w2, w1_inv, w2_inv, m1[40], m2[40], m1_inv[40], m2_inv[40];
void Solve(num &A, num *mi, long long x) {
for (int i = 0; i <= 35; i++)
if (x >> i & 1) A = A * mi[i];
}
struct fib {
num A, B;
void solve(long long x) {
if (!x) return;
if (x >= 0) {
Solve(A, m1, x), Solve(B, m2, x);
} else
Solve(A, m1_inv, -x), Solve(B, m2_inv, -x);
}
void init(long long x) {
A = {1, 0}, B = {1, 0};
solve(x);
}
friend fib operator+(fib t1, fib t2) {
return (fib){t1.A + t2.A, t1.B + t2.B};
}
friend fib operator*(fib t1, fib t2) {
return (fib){t1.A * t2.A, t1.B * t2.B};
}
} res;
int a[2][maxn];
struct node {
long long mx[2], mn[2];
fib f;
long long lazy[2];
void puttag(long long a[2]) {
if (!a[0] && !a[1]) return;
for (int i = 0; i < 2; i++) lazy[i] += a[i], mx[i] += a[i], mn[i] += a[i];
f.solve(a[0] + a[1]);
}
} tr[maxn * 4];
void pushup(int root) {
for (int i = 0; i < 2; i++) {
tr[root].mx[i] = max(tr[root << 1].mx[i], tr[root << 1 | 1].mx[i]),
tr[root].mn[i] = min(tr[root << 1].mn[i], tr[root << 1 | 1].mn[i]);
}
tr[root].f = tr[root << 1].f + tr[root << 1 | 1].f;
}
void pushdown(int root) {
tr[root << 1].puttag(tr[root].lazy);
tr[root << 1 | 1].puttag(tr[root].lazy);
tr[root].lazy[0] = tr[root].lazy[1] = 0;
}
void build(int l, int r, int root) {
if (l == r) {
for (int i = 0; i < 2; i++) tr[root].mx[i] = tr[root].mn[i] = a[i][l];
tr[root].f.init(a[0][l] + a[1][l]);
return;
}
int mid = (l + r) >> 1;
build(l, mid, root << 1), build(mid + 1, r, root << 1 | 1);
pushup(root);
}
void chkmin(int L, int R, int l, int r, int root, int k, long long delta) {
if (tr[root].mx[k] <= delta) return;
if (L <= l && r <= R && tr[root].mx[k] == tr[root].mn[k]) {
long long a[2];
a[k] = delta - tr[root].mx[k];
a[1 - k] = 0;
tr[root].puttag(a);
return;
}
pushdown(root);
int mid = (l + r) >> 1;
if (L <= mid) chkmin(L, R, l, mid, root << 1, k, delta);
if (mid < R) chkmin(L, R, mid + 1, r, root << 1 | 1, k, delta);
pushup(root);
}
void chkmax(int L, int R, int l, int r, int root, int k, long long delta) {
if (tr[root].mn[k] >= delta) return;
if (L <= l && r <= R && tr[root].mx[k] == tr[root].mn[k]) {
long long a[2];
a[k] = delta - tr[root].mx[k];
a[1 - k] = 0;
tr[root].puttag(a);
return;
}
pushdown(root);
int mid = (l + r) >> 1;
if (L <= mid) chkmax(L, R, l, mid, root << 1, k, delta);
if (mid < R) chkmax(L, R, mid + 1, r, root << 1 | 1, k, delta);
pushup(root);
}
void add(int L, int R, int l, int r, int root, int k, long long delta) {
if (L <= l && r <= R) {
long long a[2];
a[k] = delta;
a[1 - k] = 0;
tr[root].puttag(a);
return;
}
pushdown(root);
int mid = (l + r) >> 1;
if (L <= mid) add(L, R, l, mid, root << 1, k, delta);
if (mid < R) add(L, R, mid + 1, r, root << 1 | 1, k, delta);
pushup(root);
}
void query(int L, int R, int l, int r, int root) {
if (L <= l && r <= R) {
res = res + tr[root].f;
return;
}
pushdown(root);
int mid = (l + r) >> 1;
if (L <= mid) query(L, R, l, mid, root << 1);
if (mid < R) query(L, R, mid + 1, r, root << 1 | 1);
}
int main() {
w1 = {inv2, inv2}, w2 = {inv2, mod - inv2};
w1_inv = w1.inv(), w2_inv = w2.inv();
m1[0] = w1, m2[0] = w2, m1_inv[0] = w1_inv, m2_inv[0] = w2_inv;
for (int i = 1; i <= 39; i++)
m1[i] = m1[i - 1] * m1[i - 1], m2[i] = m2[i - 1] * m2[i - 1],
m1_inv[i] = m1_inv[i - 1] * m1_inv[i - 1],
m2_inv[i] = m2_inv[i - 1] * m2_inv[i - 1];
read(n), read(q);
for (int i = 0; i < 2; i++)
for (int j = 1; j <= n; j++) read(a[i][j]);
build(1, n, 1);
int op, l, r, k;
long long delta;
while (q--) {
read(op);
if (op == 4) {
read(l), read(r);
res = (fib){(num){0, 0}, (num){0, 0}};
query(l, r, 1, n, 1);
num tmp = res.A - res.B;
printf("%d\n", tmp.b % mod);
} else {
read(k), k--, read(l), read(r);
read(delta);
if (op == 1)
chkmin(l, r, 1, n, 1, k, delta);
else if (op == 2)
chkmax(l, r, 1, n, 1, k, delta);
else
add(l, r, 1, n, 1, k, delta);
}
}
return 0;
}
|
In the year 2420 humans have finally built a colony on Mars thanks to the work of Elon Tusk. There are 10^9+7 cities arranged in a circle in this colony and none of them are connected yet. Elon Tusk wants to connect some of those cities using only roads of the same size in order to lower the production cost of those roads. Because of that he gave a list on N cites where some cites can appear more than once and Q queries that you need to answer. For the query you need to determine if it is possible to connect all the cities from L_{i} to R_{i} on that list using only roads of length D_{i}.
Input
The first line contains two integers N and Q (1 ≤ N, Q ≤ 2⋅10^5 ) — the length of the array of cities and the number of queries you need to answer.
The second lines contains N integers representing the array of cites. Next Q lines contain three integers L, R and D (1 ≤ L_{i}, R_{i} ≤ N, 0 ≤ D_{i} ≤ 10^9+6) — the range of cities that needs to be connected and the length of the road that you can use.
Output
The output contains Q lines. If it is possible to connect all the cities from the i-th query can be connected with roads of length D_{i} the i-th line should contain the word "Yes", otherwise it should contain the word "No".
Examples
Input
9 8
17 0 12 6 10 8 2 4 5
2 3 12
2 3 6
2 4 6
4 6 2
2 8 2
1 2 17
1 8 2
9 9 14
Output
Yes
No
Yes
Yes
Yes
Yes
No
Yes
Input
4 1
7 21 14 0
1 4 1000000000
Output
Yes
Note
In the 5^{th} query of the first test case we can connect cities in this order 0-2-4-6-8-10-12 this way distance between any two connected cities is 2. In the second test case we can connect cities in this order 21-14-7-0 this way distance between any two connected cities is 10^9 module 10^9+7. | #include <bits/stdc++.h>
using namespace std;
const int N = 200010, mo = 1e9 + 7;
int n, q;
long long a[N], s1[N], s2[N], c[N];
long long qmi(long long a, long long k) {
long long res = 1;
while (k) {
if (k & 1) res = res * a % mo;
a = a * a % mo;
k >>= 1;
}
return res;
}
long long mod(long long x) { return (x % mo + mo) % mo; }
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
for (long long i = 1; i <= n; i++) {
cin >> a[i];
s1[i] = (s1[i - 1] + a[i]) % mo;
s2[i] = (s2[i - 1] + a[i] * a[i] % mo) % mo;
c[i] = (c[i - 1] + i * i % mo) % mo;
}
long long l, r, d, len;
while (q--) {
cin >> l >> r >> d;
len = r - l + 1;
long long f1 = (s1[r] - s1[l - 1]), f2 = (s2[r] - s2[l - 1]);
f1 = mod(f1), f2 = mod(f2);
long long f = (f1 * 2 * qmi(len, mo - 2) % mo - (len - 1) * d % mo) % mo *
qmi(2, mo - 2) % mo;
f = mod(f);
long long ans = f * f % mo * len % mo +
f * (len - 1) % mo * len % mo * d % mo +
c[len - 1] * d % mo * d % mo;
ans = mod(ans);
if (ans == f2)
puts("Yes");
else
puts("No");
}
return 0;
}
|
You are given N points on an infinite plane with the Cartesian coordinate system on it. N-1 points lay on one line, and one point isn't on that line. You are on point K at the start, and the goal is to visit every point. You can move between any two points in a straight line, and you can revisit points. What is the minimum length of the path?
Input
The first line contains two integers: N (3 ≤ N ≤ 2*10^5) - the number of points, and K (1 ≤ K ≤ N) - the index of the starting point.
Each of the next N lines contain two integers, A_i, B_i (-10^6 ≤ A_i, B_i ≤ 10^6) - coordinates of the i-th point.
Output
The output contains one number - the shortest path to visit all given points starting from point K. The absolute difference between your solution and the main solution shouldn't exceed 10^-6;
Example
Input
5 2
0 0
-1 1
2 -2
0 1
-2 2
Output
7.478709
Note
The shortest path consists of these moves:
2 -> 5
5 -> 4
4 -> 1
1 -> 3
There isn't any shorter path possible. | #include <bits/stdc++.h>
using namespace std;
const int DIM = 2e5 + 5;
struct point {
int x, y;
point() : x(0), y(0){};
};
bool colinear(point a, point b, point c) {
if (1LL * (a.x - b.x) * (a.y - c.y) == 1LL * (a.x - c.x) * (a.y - b.y)) {
if (a.x - b.x == 0) {
if (a.x - c.x == 0) return true;
return false;
}
if (a.y - b.y == 0) {
if (a.y - c.y == 0) return true;
return false;
}
return true;
}
return false;
}
long double dist(point a, point b) {
return sqrt((long double)(a.x - b.x) * (a.x - b.x) +
(long double)(a.y - b.y) * (a.y - b.y));
}
int n, k;
point a[DIM];
vector<int> get_pair(int x, int y) {
auto X = a[x];
auto Y = a[y];
vector<int> sol;
sol.push_back(x);
sol.push_back(y);
for (int i = 1; i <= n; ++i) {
if (i == x || i == y) continue;
if (colinear(X, Y, a[i])) sol.push_back(i);
}
return sol;
}
long double calc(vector<point> &v, point &out) {
long double ans = 1e18;
long double le = 0;
for (int i = 1; i < (int)v.size(); ++i) le = le + dist(v[i], v[i - 1]);
for (int i = 1; i < (int)v.size(); ++i)
ans = min(ans, le - dist(v[i], v[i - 1]) + dist(v[i - 1], out) +
min(dist(v[i], out), dist(v.back(), out)));
ans = min(ans, le + dist(v.back(), out));
return ans;
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; ++i) scanf("%d%d", &a[i].x, &a[i].y);
vector<int> ind = get_pair(1, 2);
if ((int)ind.size() != n - 1) ind = get_pair(3, 4);
sort(ind.begin(), ind.end(), [](int x, int y) {
if (a[x].x != a[y].x) return a[x].x < a[y].x;
return a[x].y < a[y].y;
});
bool found = false;
vector<int> ap(n + 1, 0);
for (auto it : ind) {
ap[it] = true;
if (it == k) found = true;
}
point out;
for (int i = 1; i <= n; ++i)
if (!ap[i]) out = a[i];
long double ans = 1e18;
if (!found) {
ans = dist(a[ind[0]], a[ind.back()]) +
min(dist(a[ind[0]], a[k]), dist(a[ind.back()], a[k]));
} else {
int wh = -1;
long double le = dist(a[ind.back()], a[ind[0]]);
for (int i = 0; i < (int)ind.size(); ++i)
if (ind[i] == k) wh = i;
if (wh + 1 < (int)ind.size())
ans = min(ans,
le - dist(a[k], a[ind[wh + 1]]) + dist(a[ind[0]], out) +
min(dist(a[ind[wh + 1]], out), dist(a[ind.back()], out)));
else
ans = min(ans, le + dist(a[ind[0]], out));
if (wh - 1 >= 0)
ans =
min(ans, le - dist(a[k], a[ind[wh - 1]]) + dist(a[ind.back()], out) +
min(dist(a[ind[wh - 1]], out), dist(a[ind[0]], out)));
else
ans = min(ans, le + dist(a[ind.back()], out));
vector<point> v;
for (int i = wh; i < (int)ind.size(); ++i) v.push_back(a[ind[i]]);
for (int i = wh - 1; i >= 0; --i) v.push_back(a[ind[i]]);
ans = min(ans, calc(v, out));
v.clear();
for (int i = wh; i >= 0; --i) v.push_back(a[ind[i]]);
for (int i = wh + 1; i < (int)ind.size(); ++i) v.push_back(a[ind[i]]);
ans = min(ans, calc(v, out));
}
printf("%0.9Lf", ans);
return 0;
}
|
This is an interactive problem!
As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant 10^9 × 10^9 grid, with squares having both coordinates between 1 and 10^9.
You know that the enemy base has the shape of a rectangle, with the sides parallel to the sides of the grid. The people of your world are extremely scared of being at the edge of the world, so you know that the base doesn't contain any of the squares on the edges of the grid (the x or y coordinate being 1 or 10^9).
To help you locate the base, you have been given a device that you can place in any square of the grid, and it will tell you the manhattan distance to the closest square of the base. The manhattan distance from square (a, b) to square (p, q) is calculated as |a−p|+|b−q|. If you try to place the device inside the enemy base, you will be captured by the enemy. Because of this, you need to make sure to never place the device inside the enemy base.
Unfortunately, the device is powered by a battery and you can't recharge it. This means that you can use the device at most 40 times.
Input
The input contains the answers to your queries.
Interaction
Your code is allowed to place the device on any square in the grid by writing "? i j" (1 ≤ i,j ≤ 10^9). In return, it will recieve the manhattan distance to the closest square of the enemy base from square (i,j) or -1 if the square you placed the device on is inside the enemy base or outside the grid.
If you recieve -1 instead of a positive number, exit immidiately and you will see the wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Your solution should use no more than 40 queries.
Once you are sure where the enemy base is located, you should print "! x y p q" (1 ≤ x ≤ p≤ 10^9, 1 ≤ y ≤ q≤ 10^9), where (x, y) is the square inside the enemy base with the smallest x and y coordinates, and (p, q) is the square inside the enemy base with the largest x and y coordinates. Note that answering doesn't count as one of the 40 queries.
After printing a query or printing the answer, 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 the documentation for other languages.
Example
Input
1
1
2
1
Output
? 2 2
? 5 5
? 4 7
? 1 5
! 2 3 4 5 | #include <bits/stdc++.h>
using namespace std;
inline int read(void) {
register int x = 0, sgn = 1, ch = getchar();
while (ch < 48 || 57 < ch) {
if (ch == 45) sgn = 0;
ch = getchar();
}
while (47 < ch && ch < 58) {
x = x * 10 + ch - 48;
ch = getchar();
}
return sgn ? x : -x;
}
void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int d[4];
int D;
int drl, dub;
signed main() {
printf("? 1 1\n");
fflush(stdout);
scanf("%d", &d[0]);
printf("? 1000000000 1\n");
fflush(stdout);
scanf("%d", &d[1]);
printf("? 1 1000000000\n");
fflush(stdout);
scanf("%d", &d[2]);
int R = 999999999;
int L = 2;
while (L < R) {
int Mid = (L + R + 1) / 2;
printf("? %d 1\n", Mid);
fflush(stdout);
scanf("%d", &D);
if (D + Mid - 1 == d[0]) {
L = Mid;
} else
R = Mid - 1;
}
printf("? %d 1\n", L);
fflush(stdout);
scanf("%d", &D);
int l = d[0] - D + 1;
int b = D + 1;
int r = d[1] - D + 1;
int u = d[2] - l + 2;
printf("! %d %d %d %d\n", l, b, 1000000001 - r, 1000000001 - u);
return 0;
}
|
You are given an undirected graph of N nodes and M edges, E_1, E_2, ... E_M.
A connected graph is a cactus if each of it's edges belogs to at most one simple cycle. A graph is a desert if each of it's connected components is a cactus.
Find the number of pairs (L, R), (1 ≤ L ≤ R ≤ M) such that, if we delete all the edges except for E_L, E_{L+1}, ... E_R, the graph is a desert.
Input
The first line contains two integers N and M (2 ≤ N ≤ 2.5 × 10^5, 1 ≤ M ≤ 5 × 10^5). Each of the next M lines contains two integers. The i-th line describes the i-th edge. It contains integers U_i and V_i, the nodes connected by the i-th edge (E_i=(U_i, V_i)). It is guaranteed that 1 ≤ U_i, V_i ≤ N and U_i ≠ V_i.
Output
The output contains one integer number – the answer.
Examples
Input
5 6
1 2
2 3
3 4
4 5
5 1
2 4
Output
20
Input
2 3
1 2
1 2
1 2
Output
5
Note
In the second example: Graphs for pairs (1, 1), (2, 2) and (3, 3) are deserts because they don't have any cycles. Graphs for pairs (1, 2) and (2, 3) have one cycle of length 2 so they are deserts. | #include <bits/stdc++.h>
using namespace std;
struct node {
int son[2], fa;
int revtag, tag, key, sum, qwq;
} t[750010];
int n, m;
inline void up(int x) {
t[x].sum = t[t[x].son[0]].sum | t[t[x].son[1]].sum | t[x].key;
t[x].qwq = t[t[x].son[0]].qwq | t[t[x].son[1]].qwq | (x > n);
}
inline void rev(int x) {
t[x].revtag ^= 1;
swap(t[x].son[0], t[x].son[1]);
}
inline void cover(int x, int k) {
t[x].tag = k;
if (x > n) t[x].key = k;
if (t[x].qwq) t[x].sum = k;
}
inline void down(int x) {
if (t[x].revtag) {
rev(t[x].son[0]);
rev(t[x].son[1]);
t[x].revtag = 0;
}
if (t[x].tag != -1) {
cover(t[x].son[0], t[x].tag);
cover(t[x].son[1], t[x].tag);
t[x].tag = -1;
}
}
inline int nroot(int x) {
return x == t[t[x].fa].son[0] || x == t[t[x].fa].son[1];
}
inline void rotate(int x) {
int f = t[x].fa, g = t[f].fa, k = x == t[f].son[1];
int b = t[x].son[k ^ 1];
t[x].son[k ^ 1] = f, t[f].son[k] = b;
if (nroot(f)) {
t[g].son[f == t[g].son[1]] = x;
}
t[x].fa = g, t[f].fa = x, t[b].fa = f;
up(f);
}
void pushall(int x) {
if (nroot(x)) pushall(t[x].fa);
down(x);
}
inline void splay(int x) {
pushall(x);
while (nroot(x)) {
int f = t[x].fa;
if (nroot(f))
rotate((x == t[f].son[0]) == (f == t[t[f].fa].son[0]) ? f : x);
rotate(x);
}
up(x);
}
inline void access(int x) {
for (int y = 0; x; y = x, x = t[x].fa) splay(x), t[x].son[1] = y, up(x);
}
inline void make_root(int x) { access(x), splay(x), rev(x); }
inline void link(int x, int y) { make_root(x), t[x].fa = y; }
inline void cut(int x, int y) {
make_root(x), access(y), splay(x);
t[x].son[1] = 0;
t[y].fa = 0;
up(x);
}
inline void getpath(int x, int y) {
make_root(x);
access(y);
splay(y);
}
int u[500010], v[500010], vis[500010];
inline int add(int x) {
getpath(u[x], v[x]);
if (t[u[x]].fa == 0) {
link(u[x], x + n);
link(x + n, v[x]);
vis[x] = 1;
return 1;
} else {
if (t[v[x]].sum) return 0;
cover(v[x], x);
return 1;
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d", u + i, v + i);
}
long long ans = 0;
for (int l = 1, r = 0; l <= m; l++) {
while (r < m && add(r + 1)) r++;
ans += r - l + 1;
if (vis[l]) {
getpath(l + n, l + n);
if (t[l + n].key) {
int qwq = t[l + n].key;
getpath(u[qwq], v[qwq]);
cover(v[qwq], 0);
cut(u[l], l + n);
cut(v[l], l + n);
cut(u[l], l + n);
cut(v[l], l + n);
link(u[qwq], qwq + n);
link(v[qwq], qwq + n);
vis[qwq] = 1;
} else {
cut(u[l], l + n);
cut(v[l], l + n);
}
} else {
getpath(u[l], v[l]);
cover(v[l], 0);
}
}
cout << ans << endl;
}
|
Bob really likes playing with arrays of numbers. That's why for his birthday, his friends bought him a really interesting machine – an array beautifier.
The array beautifier takes an array A consisting of N integers, and it outputs a new array B of length N that it constructed based on the array given to it. The array beautifier constructs the new array in the following way: it takes two numbers at different indices from the original array and writes their sum to the end of the new array. It does this step N times - resulting in an output array of length N. During this process, the machine can take the same index multiple times in different steps.
Bob was very excited about the gift that his friends gave him, so he put his favorite array in the machine. However, when the machine finished, Bob was not happy with the resulting array. He misses his favorite array very much, and hopes to get it back.
Given the array that the machine outputted, help Bob find an array that could be the original array that he put in the machine. Sometimes the machine makes mistakes, so it is possible that no appropriate input array exists for the array it has outputted. In such case, let Bob know that his array is forever lost.
Input
The first line contains one positive integer N (2 ≤ N ≤ 10^3) – the length of Bob's array.
The second line contains N integers B_1, B_2, ..., B_N (1 ≤ B_i ≤ 10^6) – the elements of the array the machine outputted.
Output
If an appropriate input array exists, print "YES", followed by the input array A_1, A_2, ..., A_N (-10^9 ≤ A_i ≤ 10^9) in the next line. Otherwise, print "NO".
Examples
Input
2
5 5
Output
YES
2 3
Input
3
1 2 3
Output
YES
0 1 2
Input
3
2 4 5
Output
NO
Input
4
1 3 5 7
Output
YES
6 -3 4 1 | #include <bits/stdc++.h>
using namespace std;
const int M = 1000000007;
const int MM = 998244353;
template <typename T, typename U>
static inline void amin(T &x, U y) {
if (y < x) x = y;
}
template <typename T, typename U>
static inline void amax(T &x, U y) {
if (x < y) x = y;
}
map<int, map<int, pair<int, int>>> mask;
int _runtimeTerror_() {
int n;
cin >> n;
vector<long long> b(n);
vector<int> even, odd;
set<int> s;
for (int i = 0; i < n; ++i) {
cin >> b[i];
if (!s.count(b[i])) {
if (b[i] & 1) {
odd.push_back(b[i]);
} else {
even.push_back(b[i]);
}
}
s.insert(b[i]);
}
if ((long long)s.size() < n) {
vector<int> ans(n, 1e8);
ans[0] = 0;
s.clear();
int cur = 1;
for (int i = 0; i < n; ++i) {
if (s.count(b[i])) {
continue;
}
ans[cur] = b[i];
++cur;
s.insert(b[i]);
}
cout << "YES\n";
for (int i = 0; i < n; ++i) {
cout << ans[i] << " ";
}
cout << "\n";
return 0;
}
if (n == 2) {
cout << "NO\n";
return 0;
}
if (n == 3) {
int sum = b[0] + b[1] + b[2];
if (sum % 2) {
cout << "NO\n";
return 0;
}
sum /= 2;
cout << "YES\n";
cout << sum - b[0] << " " << sum - b[1] << " " << sum - b[2] << "\n";
return 0;
}
assert(n >= 4);
if (even.empty()) {
int nn = min(n, 24);
vector<int> left, right;
for (int i = 0; i < (nn + 1) / 2; ++i) {
left.push_back(b[i]);
}
for (int i = 0; i < nn / 2; ++i) {
right.push_back(b[nn - 1 - i]);
}
reverse(right.begin(), right.end());
int tmp = (long long)right.size();
assert((long long)left.size() + (long long)right.size() == nn);
mask[0][0] = {0, 0};
for (int i = 0; i < (1 << tmp); ++i) {
for (int j = i; j; j = (j - 1) & i) {
int val = 0, f = 0;
for (int k = 0; k < tmp; ++k) {
if ((i & (1 << k)) && ((j & (1 << k)) == 0)) {
val += right[k];
++f;
} else if (i & (1 << k)) {
val -= right[k];
--f;
}
}
mask[f][val] = {i, j};
}
}
tmp = (long long)left.size();
pair<int, int> ans = {-1, -1};
if (mask[0][0].first != 0) {
ans = mask[0][0];
ans.first <<= tmp;
ans.second <<= tmp;
}
for (int i = 0; i < (1 << tmp); ++i) {
if (ans.first != -1) {
break;
}
for (int j = i; j; j = (j - 1) & i) {
int val = 0, f = 0;
for (int k = 0; k < tmp; ++k) {
if ((i & (1 << k)) && ((j & (1 << k)) == 0)) {
val += left[k];
++f;
} else if (i & (1 << k)) {
val -= left[k];
--f;
}
}
if (mask.count(-f) && mask[-f].count(-val)) {
ans = mask[-f][-val];
ans.first <<= tmp;
ans.second <<= tmp;
ans.first |= i;
ans.second |= j;
break;
}
}
if (ans.first != -1) {
break;
}
}
if (ans.first == -1) {
cout << "NO\n";
return 0;
}
assert(__builtin_popcountll(ans.first) ==
2 * __builtin_popcountll(ans.second));
vector<int> lx, rx, tt;
for (int i = 0; i < nn; ++i) {
if ((ans.first & (1 << i)) && (ans.second & (1 << i))) {
rx.push_back(b[i]);
} else if (ans.first & (1 << i)) {
lx.push_back(b[i]);
} else {
tt.push_back(b[i]);
}
}
assert((long long)lx.size() == (long long)rx.size());
cout << "YES\n";
int cur = 0;
for (int i = 0; i < (long long)lx.size(); ++i) {
cout << lx[i] - cur << " ";
cur = lx[i] - cur;
cout << rx[i] - cur << " ";
cur = rx[i] - cur;
}
for (auto &j : tt) {
cout << j - cur << " ";
}
for (int i = nn; i < n; ++i) {
cout << b[i] - cur << " ";
}
cout << "\n";
return 0;
}
vector<int> t;
int cnt = min(3ll, (long long)even.size());
for (int i = 0; i < cnt; ++i) {
t.push_back(even.back());
even.pop_back();
}
if ((long long)t.size() % 2 == 0) {
even.push_back(t.back());
t.pop_back();
}
while ((long long)t.size() < 3) {
t.push_back(odd.back());
odd.pop_back();
}
int sum = accumulate(t.begin(), t.end(), 0);
assert(sum % 2 == 0);
cout << "YES\n";
sum /= 2;
cout << sum - t[0] << " " << sum - t[1] << " " << sum - t[2] << " ";
for (int i : even) {
cout << i - (sum - t[0]) << " ";
}
for (int i : odd) {
cout << i - (sum - t[0]) << " ";
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int TESTS = 1;
while (TESTS--) _runtimeTerror_();
return 0;
}
|
Alice and Bob are playing a game. They are given an array A of length N. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game?
Input
The first line contains one integer N (1 ≤ N ≤ 2*10^5) - the length of the array A.
The second line contains N integers A_1, A_2,...,A_N (0 ≤ A_i ≤ 10^9)
Output
The first and only line of output consists of one string, the name of the winner. If Alice won, print "Alice", otherwise, print "Bob".
Examples
Input
1
5
Output
Alice
Input
3
5 4 5
Output
Alice
Input
6
5 8 2 1 10 9
Output
Bob | from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
#from collections import deque, Counter, OrderedDict, defaultdict
#import heapq
#ceil,floor,log,sqrt,factorial,pow,pi,gcd
#import bisect
#from bisect import bisect_left,bisect_right
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):
"""Prints the values to a stream, or to sys.stdout by default."""
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")
def inp():
return(int(input()))
def inps():
return input().strip()
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
n=inp()
l=inlt()
array=0
chnce={'Alice':'Bob','Bob':'Alice'}
strt='Alice'
cntl=1
cntr=1
for i in range(1,n):
if l[i]>l[i-1]:
cntl+=1
else:
break
for i in range(n-2,-1,-1):
if l[i]>l[i+1]:
cntr+=1
else:
break
# print(cntl,cntr)
if cntl%2 or cntr%2:
print(strt)
else:
print(chnce[strt]) |
On the great island of Baltia, there live N people, numbered from 1 to N. There are exactly M pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party is a gathering of exactly 5 people. The party is considered to be successful if either all the people at the party are friends with each other (so that they can all talk to each other without having to worry about talking to someone they are not friends with) or no two people at the party are friends with each other (so that everyone can just be on their phones without anyone else bothering them). Please help the people of Baltia organize a successful party or tell them that it's impossible to do so.
Input
The first line contains two integer numbers, N (5 ≤ N ≤ 2*10^5) and M (0 ≤ M ≤ 2*10^5) – the number of people that live in Baltia, and the number of friendships. The next M lines each contains two integers U_i and V_i (1 ≤ U_i,V_i ≤ N) – meaning that person U_i is friends with person V_i. Two friends can not be in the list of friends twice (no pairs are repeated) and a person can be friends with themselves (U_i ≠ V_i).
Output
If it's possible to organize a successful party, print 5 numbers indicating which 5 people should be invited to the party. If it's not possible to organize a successful party, print -1 instead. If there are multiple successful parties possible, print any.
Examples
Input
6 3
1 4
4 2
5 4
Output
1 2 3 5 6
Input
5 4
1 2
2 3
3 4
4 5
Output
-1 | #include <bits/stdc++.h>
using namespace std;
const int mxN = 1000006, mod = 1e9 + 7, LOG = 23;
int n, m, u, v;
bool veze[55][55];
bool check(int i1, int i2, int i3, int i4, int i5) {
if (veze[i1][i2] && veze[i1][i3] && veze[i1][i4] && veze[i1][i5]) {
if (veze[i2][i3] && veze[i2][i4] && veze[i2][i5]) {
if (veze[i3][i4] && veze[i3][i5]) {
if (veze[i4][i5]) {
return 1;
}
}
}
}
if (!veze[i1][i2] && !veze[i1][i3] && !veze[i1][i4] && !veze[i1][i5]) {
if (!veze[i2][i3] && !veze[i2][i4] && !veze[i2][i5]) {
if (!veze[i3][i4] && !veze[i3][i5]) {
if (!veze[i4][i5]) {
return 1;
}
}
}
}
return 0;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
if (u <= 50 && v <= 50) {
veze[u][v] = 1;
veze[v][u] = 1;
}
}
int kr = min(n, 50);
for (int i = 1; i <= kr; i++) {
for (int j = i + 1; j <= kr; j++) {
for (int z = j + 1; z <= kr; z++) {
for (int k = z + 1; k <= kr; k++) {
for (int p = k + 1; p <= kr; p++) {
if (check(i, j, z, k, p)) {
cout << i << " " << j << " " << z << " " << k << " " << p << '\n';
return 0;
}
}
}
}
}
}
cout << -1 << '\n';
return 0;
}
|
You have received data from a Bubble bot. You know your task is to make factory facilities, but before you even start, you need to know how big the factory is and how many rooms it has. When you look at the data you see that you have the dimensions of the construction, which is in rectangle shape: N x M.
Then in the next N lines you have M numbers. These numbers represent factory tiles and they can go from 0 to 15. Each of these numbers should be looked in its binary form. Because from each number you know on which side the tile has walls. For example number 10 in it's binary form is 1010, which means that it has a wall from the North side, it doesn't have a wall from the East, it has a wall on the South side and it doesn't have a wall on the West side. So it goes North, East, South, West.
It is guaranteed that the construction always has walls on it's edges. The input will be correct.
Your task is to print the size of the rooms from biggest to smallest.
Input
The first line has two numbers which are N and M, the size of the construction. Both are integers:
n (1 ≤ n ≤ 10^3)
m (1 ≤ m ≤ 10^3)
Next N x M numbers represent each tile of construction.
Output
Once you finish processing the data your output consists of one line sorted from biggest to smallest room sizes.
Example
Input
4 5
9 14 11 12 13
5 15 11 6 7
5 9 14 9 14
3 2 14 3 14
Output
9 4 4 2 1 |
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
if(other.index < this.index) return 1;
if(other.index > this.index) return -1;
if(other.value < this.value) return 1;
if(other.value > this.value) return -1;
else return 0;
}
@Override
public String toString() {
return this.index + " " + this.value;
}
}
static boolean isPrime(long d) {
if (d == 1)
return false;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static void decimalTob(int n, int k, Stack<Integer> ss) {
int x = n % k;
int y = n / k;
ss.push(x);
if(y > 0) {
decimalTob(y, k, ss);
}
}
static int[] binaryArray(int n) {
int x = n;
Stack<Integer> ss = new Stack<>();
for(int i = 0; i < 3; i++) {
ss.add(x % 2);
x /= 2;
}
ss.add(x);
int arr[] = new int[4];
for(int i = 0; i < 4; i++) arr[i] = ss.pop();
return arr;
}
static long powermod(long x, long y, long mod) {
long ans = 1;
x = x % mod;
if (x == 0)
return 0;
int i = 1;
while (y > 0) {
if ((y & 1) != 0)
ans = (ans * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return ans;
}
static int dfs(int node, int i, int j, int arr[][], HashMap<Integer, int[]> ss, boolean hachu[]) {
if(hachu[node]) return 0;
hachu[node] = true;
int count = 1;
int temp[] = ss.get(node);
if(temp[0] == 0) count += dfs(arr[i - 1][j], i - 1, j, arr, ss, hachu);
if(temp[1] == 0) count += dfs(arr[i][j + 1], i, j + 1, arr, ss, hachu);
if(temp[2] == 0) count += dfs(arr[i + 1][j], i + 1, j, arr, ss, hachu);
if(temp[3] == 0) count += dfs(arr[i][j - 1], i, j - 1, arr, ss, hachu);
return count;
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int crr[][] = new int[16][];
for(int i = 0; i < 16; i++) crr[i] = binaryArray(i);
int t = 1;
while(t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int arr[][] = new int[n][m];
int brr[][] = new int[n][m];
int k = 1;
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
brr[i][j] = k++;
}
HashMap<Integer, int[]> ss = new HashMap<>();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
ss.put(brr[i][j], crr[arr[i][j]]);
}
}
boolean hachu[] = new boolean[k];
ArrayList<Integer> ssd = new ArrayList<>();
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(!hachu[brr[i][j]]) {
ssd.add(dfs(brr[i][j], i, j, brr, ss, hachu));
}
Collections.sort(ssd, Collections.reverseOrder());
for(int e: ssd) out.print(e + " ");
}
out.close();
}
} |
You are given array a_1, a_2, …, a_n, consisting of non-negative integers.
Let's define operation of "elimination" with integer parameter k (1 ≤ k ≤ n) as follows:
* Choose k distinct array indices 1 ≤ i_1 < i_2 < … < i_k ≤ n.
* Calculate x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ … ~ \& ~ a_{i_k}, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND) (notes section contains formal definition).
* Subtract x from each of a_{i_1}, a_{i_2}, …, a_{i_k}; all other elements remain untouched.
Find all possible values of k, such that it's possible to make all elements of array a equal to 0 using a finite number of elimination operations with parameter k. It can be proven that exists at least one possible k for any array a.
Note that you firstly choose k and only after that perform elimination operations with value k you've chosen initially.
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 one integer n (1 ≤ n ≤ 200 000) — the length of array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≤ a_i < 2^{30}) — array a itself.
It's guaranteed that the sum of n over all test cases doesn't exceed 200 000.
Output
For each test case, print all values k, such that it's possible to make all elements of a equal to 0 in a finite number of elimination operations with the given parameter k.
Print them in increasing order.
Example
Input
5
4
4 4 4 4
4
13 7 25 19
6
3 5 3 1 7 1
1
1
5
0 0 0 0 0
Output
1 2 4
1 2
1
1
1 2 3 4 5
Note
In the first test case:
* If k = 1, we can make four elimination operations with sets of indices \{1\}, \{2\}, \{3\}, \{4\}. Since \& of one element is equal to the element itself, then for each operation x = a_i, so a_i - x = a_i - a_i = 0.
* If k = 2, we can make two elimination operations with, for example, sets of indices \{1, 3\} and \{2, 4\}: x = a_1 ~ \& ~ a_3 = a_2 ~ \& ~ a_4 = 4 ~ \& ~ 4 = 4. For both operations x = 4, so after the first operation a_1 - x = 0 and a_3 - x = 0, and after the second operation — a_2 - x = 0 and a_4 - x = 0.
* If k = 3, it's impossible to make all a_i equal to 0. After performing the first operation, we'll get three elements equal to 0 and one equal to 4. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to 0.
* If k = 4, we can make one operation with set \{1, 2, 3, 4\}, because x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4 = 4.
In the second test case, if k = 2 then we can make the following elimination operations:
* Operation with indices \{1, 3\}: x = a_1 ~ \& ~ a_3 = 13 ~ \& ~ 25 = 9. a_1 - x = 13 - 9 = 4 and a_3 - x = 25 - 9 = 16. Array a will become equal to [4, 7, 16, 19].
* Operation with indices \{3, 4\}: x = a_3 ~ \& ~ a_4 = 16 ~ \& ~ 19 = 16. a_3 - x = 16 - 16 = 0 and a_4 - x = 19 - 16 = 3. Array a will become equal to [4, 7, 0, 3].
* Operation with indices \{2, 4\}: x = a_2 ~ \& ~ a_4 = 7 ~ \& ~ 3 = 3. a_2 - x = 7 - 3 = 4 and a_4 - x = 3 - 3 = 0. Array a will become equal to [4, 4, 0, 0].
* Operation with indices \{1, 2\}: x = a_1 ~ \& ~ a_2 = 4 ~ \& ~ 4 = 4. a_1 - x = 4 - 4 = 0 and a_2 - x = 4 - 4 = 0. Array a will become equal to [0, 0, 0, 0].
Formal definition of bitwise AND:
Let's define bitwise AND (\&) as follows. Suppose we have two non-negative integers x and y, let's look at their binary representations (possibly, with leading zeroes): x_k ... x_2 x_1 x_0 and y_k ... y_2 y_1 y_0. Here, x_i is the i-th bit of number x, and y_i is the i-th bit of number y. Let r = x ~ \& ~ y is a result of operation \& on number x and y. Then binary representation of r will be r_k ... r_2 r_1 r_0, where:
$$$ r_i = \begin{cases} 1, ~ if ~ x_i = 1 ~ and ~ y_i = 1 \\\ 0, ~ if ~ x_i = 0 ~ or ~ y_i = 0 \end{cases} $$$ | #include <bits/stdc++.h>
int n, a[200011], buc[30];
int gcd(int a, int b) { return !b ? a : gcd(b, a % b); }
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", a + i);
for (int i = 0; i < 30; ++i) buc[i] = 0;
for (int i = 1; i <= n; ++i)
for (int j = 0; j < 30; ++j)
if (a[i] >> j & 1) ++buc[j];
int x = 0;
for (int i = 0; i < 30; ++i) x = gcd(x, buc[i]);
for (int i = 1; i <= n; ++i) {
if (x % i == 0) printf("%d ", i);
}
putchar(10);
}
return 0;
}
|
Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of n meters depth. Now Gorf is on the bottom of the well and has a long way up.
The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on x meters below ground level, then in one jump he can go up on any integer distance from 0 to a_x meters inclusive. (Note that Gorf can't jump down, only up).
Unfortunately, Gorf has to take a break after each jump (including jump on 0 meters). And after jumping up to position x meters below ground level, he'll slip exactly b_x meters down while resting.
Calculate the minimum number of jumps Gorf needs to reach ground level.
Input
The first line contains a single integer n (1 ≤ n ≤ 300 000) — the depth of the well.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ i), where a_i is the maximum height Gorf can jump from i meters below ground level.
The third line contains n integers b_1, b_2, …, b_n (0 ≤ b_i ≤ n - i), where b_i is the distance Gorf will slip down if he takes a break on i meters below ground level.
Output
If Gorf can't reach ground level, print -1. Otherwise, firstly print integer k — the minimum possible number of jumps.
Then print the sequence d_1,\,d_2, …,\,d_k where d_j is the depth Gorf'll reach after the j-th jump, but before he'll slip down during the break. Ground level is equal to 0.
If there are multiple answers, print any of them.
Examples
Input
3
0 2 2
1 1 0
Output
2
1 0
Input
2
1 1
1 0
Output
-1
Input
10
0 1 2 3 5 5 6 7 8 5
9 8 7 1 5 4 3 2 0 0
Output
3
9 4 0
Note
In the first example, Gorf is on the bottom of the well and jump to the height 1 meter below ground level. After that he slip down by meter and stays on height 2 meters below ground level. Now, from here, he can reach ground level in one jump.
In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level.
In the third example, Gorf can reach ground level only from the height 5 meters below the ground level. And Gorf can reach this height using a series of jumps 10 ⇒ 9 \dashrightarrow 9 ⇒ 4 \dashrightarrow 5 where ⇒ is the jump and \dashrightarrow is slipping during breaks. | #include <bits/stdc++.h>
using namespace std;
const int M = 3e5 + 5;
int a[M], b[M], c, lst[M], sl[M], ans[M];
struct D {
int p1, p, s;
};
queue<D> q;
int read() {
int s = 0, t = 1;
char ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-') t = -1;
for (; isdigit(ch); ch = getchar()) s = s * 10 + ch - '0';
return s * t;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) a[i] = read();
for (int i = 1; i <= n; i++) b[i] = read();
int h = n;
q.push({n, n, 0});
while (!q.empty()) {
int p1 = q.front().p1, p = q.front().p, s = q.front().s;
q.pop();
if (!p) {
c = s;
break;
}
for (int i = h - 1; i >= p - a[p]; i--)
lst[i] = p1, q.push({i, i + b[i], s + 1}), h = i;
}
if (!c) return printf("-1"), 0;
printf("%d\n", c);
for (int i = 1, x = 0; i <= c; i++, x = lst[x]) ans[i] = x;
for (int i = c; i; i--) printf("%d ", ans[i]);
}
|
You are given two arrays of integers a_1, a_2, …, a_n and b_1, b_2, …, b_m.
You need to insert all elements of b into a in an arbitrary way. As a result you will get an array c_1, c_2, …, c_{n+m} of size n + m.
Note that you are not allowed to change the order of elements in a, while you can insert elements of b at arbitrary positions. They can be inserted at the beginning, between any elements of a, or at the end. Moreover, elements of b can appear in the resulting array in any order.
What is the minimum possible number of inversions in the resulting array c? Recall that an inversion is a pair of indices (i, j) such that i < j and c_i > c_j.
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 two integers n and m (1 ≤ n, m ≤ 10^6).
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
The third line of each test case contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9).
It is guaranteed that the sum of n for all tests cases in one input doesn't exceed 10^6. The sum of m for all tests cases doesn't exceed 10^6 as well.
Output
For each test case, print one integer — the minimum possible number of inversions in the resulting array c.
Example
Input
3
3 4
1 2 3
4 3 2 1
3 3
3 2 1
1 2 3
5 4
1 3 5 3 1
4 3 6 1
Output
0
4
6
Note
Below is given the solution to get the optimal answer for each of the example test cases (elements of a are underscored).
* In the first test case, c = [\underline{1}, 1, \underline{2}, 2, \underline{3}, 3, 4].
* In the second test case, c = [1, 2, \underline{3}, \underline{2}, \underline{1}, 3].
* In the third test case, c = [\underline{1}, 1, 3, \underline{3}, \underline{5}, \underline{3}, \underline{1}, 4, 6]. | #include <bits/stdc++.h>
using namespace std;
int a[1001000], b[1001000], buf[1001000];
long long cnt_inv(int f[], int l, int r) {
if (r - l <= 1) return 0;
int m = (l + r) / 2;
long long ans = cnt_inv(f, l, m) + cnt_inv(f, m, r);
int tl = l, tm = m, s = l;
while (s < r) {
if (tl < m && (tm == r || f[tl] <= f[tm])) {
ans += tm - m;
buf[s++] = f[tl++];
} else
buf[s++] = f[tm++];
}
for (int i = l; i < r; i++) f[i] = buf[i];
return ans;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int i = 0; i < m; i++) scanf("%d", &b[i]);
sort(b, b + m);
priority_queue<int> pq;
long long ans = 0;
for (int i = 0; i < n; i++) {
int l = lower_bound(b, b + m, a[i]) - b;
int r = upper_bound(b, b + m, a[i]) - b;
ans += l;
pq.push(l);
pq.push(r);
pq.pop();
}
for (int i = 0; i < n; i++) {
ans -= pq.top();
pq.pop();
}
ans += cnt_inv(a, 0, n);
printf("%lld\n", ans);
}
return 0;
}
|
A group of n alpinists has just reached the foot of the mountain. The initial difficulty of climbing this mountain can be described as an integer d.
Each alpinist can be described by two integers s and a, where s is his skill of climbing mountains and a is his neatness.
An alpinist of skill level s is able to climb a mountain of difficulty p only if p ≤ s. As an alpinist climbs a mountain, they affect the path and thus may change mountain difficulty. Specifically, if an alpinist of neatness a climbs a mountain of difficulty p the difficulty of this mountain becomes max(p, a).
Alpinists will climb the mountain one by one. And before the start, they wonder, what is the maximum number of alpinists who will be able to climb the mountain if they choose the right order. As you are the only person in the group who does programming, you are to answer the question.
Note that after the order is chosen, each alpinist who can climb the mountain, must climb the mountain at that time.
Input
The first line contains two integers n and d (1 ≤ n ≤ 500 000; 0 ≤ d ≤ 10^9) — the number of alpinists and the initial difficulty of the mountain.
Each of the next n lines contains two integers s_i and a_i (0 ≤ s_i, a_i ≤ 10^9) that define the skill of climbing and the neatness of the i-th alpinist.
Output
Print one integer equal to the maximum number of alpinists who can climb the mountain if they choose the right order to do so.
Examples
Input
3 2
2 6
3 5
5 7
Output
2
Input
3 3
2 4
6 4
4 6
Output
2
Input
5 0
1 5
4 8
2 7
7 6
3 2
Output
3
Note
In the first example, alpinists 2 and 3 can climb the mountain if they go in this order. There is no other way to achieve the answer of 2.
In the second example, alpinist 1 is not able to climb because of the initial difficulty of the mountain, while alpinists 2 and 3 can go up in any order.
In the third example, the mountain can be climbed by alpinists 5, 3 and 4 in this particular order. There is no other way to achieve optimal answer. | #include <bits/stdc++.h>
#pragma warning(disable : 4996)
#pragma comment(linker, "/STACK:16777216")
using namespace std;
const int INF = 1000000000 + 1e8;
const long long LINF = 2000000000000000000;
struct elem {
int s, a;
};
void solve() {
int n, d;
cin >> n >> d;
vector<elem> good, bad;
for (int i = 0; i < n; i++) {
int si, ai;
cin >> si >> ai;
if (si < d) {
continue;
}
if (si >= ai)
good.push_back({si, ai});
else
bad.push_back({si, ai});
}
auto cmp = [](elem x, elem y) {
return x.a < y.a || x.a == y.a && x.s < y.s;
};
sort((good).begin(), (good).end(), cmp);
sort((bad).begin(), (bad).end(), cmp);
good.insert(good.begin(), {INF, d});
good.push_back({INF, INF});
vector<int> suffMin(int(good.size()));
suffMin[int(good.size()) - 1] = good.back().s;
for (int i = int(good.size()) - 2; i >= 0; i--)
suffMin[i] = min(suffMin[i + 1], good[i].s);
int ans = int(good.size()) - 2;
int j = 0;
vector<elem> res;
int curA = d;
for (int i = 0; i < int(good.size()) - 1; i++) {
curA = max(good[i].a, curA);
for (; j < int(bad.size()) && bad[j].a <= suffMin[i + 1]; j++) {
if (bad[j].s >= curA) {
ans++;
curA = max(curA, bad[j].a);
res.push_back(bad[j]);
}
}
}
cout << ans;
}
int main() {
srand(time(0));
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int tst = 1;
while (tst--) {
solve();
}
}
|
Students of one unknown college don't have PE courses. That's why q of them decided to visit a gym nearby by themselves. The gym is open for n days and has a ticket system. At the i-th day, the cost of one ticket is equal to a_i. You are free to buy more than one ticket per day.
You can activate a ticket purchased at day i either at day i or any day later. Each activated ticket is valid only for k days. In other words, if you activate ticket at day t, it will be valid only at days t, t + 1, ..., t + k - 1.
You know that the j-th student wants to visit the gym at each day from l_j to r_j inclusive. Each student will use the following strategy of visiting the gym at any day i (l_j ≤ i ≤ r_j):
1. person comes to a desk selling tickets placed near the entrance and buy several tickets with cost a_i apiece (possibly, zero tickets);
2. if the person has at least one activated and still valid ticket, they just go in. Otherwise, they activate one of tickets purchased today or earlier and go in.
Note that each student will visit gym only starting l_j, so each student has to buy at least one ticket at day l_j.
Help students to calculate the minimum amount of money they have to spend in order to go to the gym.
Input
The first line contains three integers n, q and k (1 ≤ n, q ≤ 300 000; 1 ≤ k ≤ n) — the number of days, the number of students and the number of days each ticket is still valid.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the cost of one ticket at the corresponding day.
Each of the next q lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the segment of days the corresponding student want to visit the gym.
Output
For each student, print the minimum possible amount of money they have to spend in order to go to the gym at desired days.
Example
Input
7 5 2
2 15 6 3 7 5 6
1 2
3 7
5 5
7 7
3 5
Output
2
12
7
6
9
Note
Let's see how each student have to spend their money:
* The first student should buy one ticket at day 1.
* The second student should buy one ticket at day 3 and two tickets at day 4. Note that student can keep purchased tickets for the next days.
* The third student should buy one ticket at day 5.
* The fourth student should buy one ticket at day 7.
* The fifth student should buy one ticket at day 3 and one at day 4. | #include <bits/stdc++.h>
using namespace std;
mt19937 rnd(time(0));
const long long mod = 1e9 + 7;
long long fastpow(long long a, long long b) {
if (b == 0) return 1;
assert(b >= 0);
if (b & 1) return fastpow(a, b - 1) * 1LL * a % mod;
long long t = fastpow(a, b / 2);
return t * 1LL * t % mod;
}
const long long maxn = 3e5 + 50;
vector<long long> r[maxn];
void solve() {
long long n, q, k;
cin >> n >> q >> k;
long long a[n];
for (auto &i : a) cin >> i;
long long sp[n][20];
for (long long i = n - 1; i >= 0; --i) {
sp[i][0] = a[i];
for (long long j = 1; j < 20; ++j) {
sp[i][j] = min(sp[i][j - 1], sp[min(n - 1, i + (1 << j - 1))][j - 1]);
}
}
long long max_st[n + 10];
long long st = 0;
for (long long i = 0; i <= n + 9; ++i) {
while ((1 << st + 1) <= i) {
st++;
}
max_st[i] = st;
}
auto get = [&](long long l, long long r) {
long long d = max_st[r - l + 1];
return min(sp[l][d], sp[r - (1 << d) + 1][d]);
};
long long bp[n][20];
vector<long long> v[k];
long long next[n][20];
for (auto &i : next)
for (auto &j : i) j = n;
for (long long i = n - 1; i >= 0; --i) {
long long dk = i % k;
long long x = get(i, min(i + k - 1, n - 1));
while (v[dk].size() &&
get(v[dk].back(), min(n - 1, v[dk].back() + k - 1)) >= x) {
v[dk].pop_back();
}
if (v[dk].size()) {
next[i][0] = v[dk].back();
bp[i][0] = x * (v[dk].back() - i) / k;
} else {
next[i][0] = n;
bp[i][0] = x * (n - i + k - 1) / k;
}
v[dk].push_back(i);
for (long long j = 1; j < 19; ++j) {
if (next[i][j - 1] != n) {
next[i][j] = next[next[i][j - 1]][j - 1];
bp[i][j] = bp[next[i][j - 1]][j - 1] + bp[i][j - 1];
} else {
bp[i][j] = bp[i][j - 1];
}
}
}
for (long long i = 0; i < q; ++i) {
long long l, r;
cin >> l >> r;
l--;
r--;
long long x = get(l, r);
if (a[l] <= x) {
cout << (r - l + 1 + k - 1) / k * a[l] << '\n';
} else {
long long d = l + 1;
for (long long j = l + 1; j + k - 1 <= r;) {
if (get(j, j + k - 1) > a[l]) {
d = j + k;
j += k;
} else {
break;
}
}
if (d + k - 1 > r) {
cout << (r - l + 1 + k - 1) / k * a[l] << '\n';
continue;
}
long long ans = a[l] * ((d - l + k - 1) / k);
long long now = d;
for (long long x = 19; x >= 0; --x) {
if (next[now][x] <= r) {
ans += bp[now][x];
now = next[now][x];
}
}
if (now + k - 1 <= r) ans += (r - now + 1) / k * get(now, now + k - 1);
cout << ans << '\n';
}
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long t = 1;
while (t--) solve();
}
|
Integers from 1 to n (inclusive) were sorted lexicographically (considering integers as strings). As a result, array a_1, a_2, ..., a_n was obtained.
Calculate value of (∑_{i = 1}^n ((i - a_i) mod 998244353)) mod 10^9 + 7.
x mod y here means the remainder after division x by y. This remainder is always non-negative and doesn't exceed y - 1. For example, 5 mod 3 = 2, (-1) mod 6 = 5.
Input
The first line contains the single integer n (1 ≤ n ≤ 10^{12}).
Output
Print one integer — the required sum.
Examples
Input
3
Output
0
Input
12
Output
994733045
Input
21
Output
978932159
Input
1000000000000
Output
289817887
Note
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.
For example, 42 is lexicographically smaller than 6, because they differ in the first digit, and 4 < 6; 42 < 420, because 42 is a prefix of 420.
Let's denote 998244353 as M.
In the first example, array a is equal to [1, 2, 3].
* (1 - 1) mod M = 0 mod M = 0
* (2 - 2) mod M = 0 mod M = 0
* (3 - 3) mod M = 0 mod M = 0
As a result, (0 + 0 + 0) mod 10^9 + 7 = 0
In the second example, array a is equal to [1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9].
* (1 - 1) mod M = 0 mod M = 0
* (2 - 10) mod M = (-8) mod M = 998244345
* (3 - 11) mod M = (-8) mod M = 998244345
* (4 - 12) mod M = (-8) mod M = 998244345
* (5 - 2) mod M = 3 mod M = 3
* (6 - 3) mod M = 3 mod M = 3
* (7 - 4) mod M = 3 mod M = 3
* (8 - 5) mod M = 3 mod M = 3
* (9 - 6) mod M = 3 mod M = 3
* (10 - 7) mod M = 3 mod M = 3
* (11 - 8) mod M = 3 mod M = 3
* (12 - 9) mod M = 3 mod M = 3
As a result, (0 + 998244345 + 998244345 + 998244345 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3) mod 10^9 + 7 = 2994733059 mod 10^9 + 7 = 994733045 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &t) {
t = 0;
char ch = getchar();
int f = 1;
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
do {
(t *= 10) += ch - '0';
ch = getchar();
} while ('0' <= ch && ch <= '9');
t *= f;
}
template <typename T>
void write(T t) {
if (t < 0) {
putchar('-');
write(-t);
return;
}
if (t > 9) write(t / 10);
putchar('0' + t % 10);
}
template <typename T>
void writeln(T t) {
write(t);
puts("");
}
const int mod = 998244353;
const int mod2 = (1e9) + 7;
long long n, cnt;
int ans, sum[10];
vector<int> vec[10];
void update(int &x, int y) {
x += y;
if (x >= mod2) x -= mod2;
}
void dfs1(int dep, int val) {
if (val > n) return;
cnt++;
vec[dep].push_back((cnt - val + mod) % mod);
if (dep == 6) return;
for (int i = 0; i < 10; i++) dfs1(dep + 1, val * 10 + i);
}
void dfs2(int dep, long long val) {
if (val > n) return;
if (dep >= 1) {
if ((long long)val * 1000000 > n / 10 &&
(long long)val * 1000000 + 999999 <= n) {
long long tmp = val;
for (int i = 0; i <= 6; i++) {
int cur = (cnt % mod - tmp % mod + mod) % mod;
update(ans, (long long)cur * (int)vec[i].size() % mod2);
int pos =
vec[i].end() - lower_bound(vec[i].begin(), vec[i].end(), mod - cur);
update(ans, (sum[i] - (long long)pos * mod % mod2 + mod2) % mod2);
tmp *= 10;
}
for (int i = 0; i <= 6; i++) cnt += (int)vec[i].size();
return;
}
cnt++;
update(ans, (cnt % mod - val % mod + mod) % mod);
}
for (int i = (dep == 0 ? 1 : 0); i < 10; i++)
dfs2(dep + 1, (long long)val * 10 + i);
}
int main() {
read(n);
dfs1(0, 0);
for (int i = 0; i <= 6; i++) {
sort(vec[i].begin(), vec[i].end());
for (int &x : vec[i]) update(sum[i], x);
}
cnt = 0;
dfs2(0, 0);
printf("%d\n", ans);
return 0;
}
|
For two positive integers l and r (l ≤ r) let c(l, r) denote the number of integer pairs (i, j) such that l ≤ i ≤ j ≤ r and \operatorname{gcd}(i, j) ≥ l. Here, \operatorname{gcd}(i, j) is the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers i and j.
YouKn0wWho has two integers n and k where 1 ≤ k ≤ n. Let f(n, k) denote the minimum of ∑_{i=1}^{k}{c(x_i+1,x_{i+1})} over all integer sequences 0=x_1 < x_2 < … < x_{k} < x_{k+1}=n.
Help YouKn0wWho find f(n, k).
Input
The first line contains a single integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of test cases.
The first and only line of each test case contains two integers n and k (1 ≤ k ≤ n ≤ 10^5).
Output
For each test case, print a single integer — f(n, k).
Example
Input
4
6 2
4 4
3 1
10 3
Output
8
4
6
11
Note
In the first test case, YouKn0wWho can select the sequence [0, 2, 6]. So f(6, 2) = c(1, 2) + c(3, 6) = 3 + 5 = 8 which is the minimum possible. | #include <bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
using ll = long long;
template <class T>
void read(T &x) {
char ch;
x = 0;
int f = 1;
while (isspace(ch = getchar_unlocked()))
;
if (ch == '-') ch = getchar_unlocked(), f = -1;
do x = x * 10 + (ch - '0');
while (isdigit(ch = getchar_unlocked()));
x *= f;
}
template <class T, class... A>
void read(T &x, A &...args) {
read(x);
read(args...);
}
const int B = 18;
const int N = 100005;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int phi[N], p[N], pc = 0;
bool np[N];
void sieve(int n) {
phi[1] = 1;
for (int i = 2; i <= n; ++i) {
if (!np[i]) p[++pc] = i, phi[i] = i - 1;
for (int j = 1; j <= pc && i * p[j] <= n; ++j) {
np[i * p[j]] = true;
if (i % p[j] == 0) {
phi[i * p[j]] = phi[i] * p[j];
break;
}
phi[i * p[j]] = phi[i] * (p[j] - 1);
}
}
}
struct node {
ll mn[B], tag;
} t[N * 4];
void up(int x) {
for (int i = 0; i < B; ++i)
t[x].mn[i] = min(t[x << 1].mn[i], t[x << 1 | 1].mn[i]) + t[x].tag;
}
void tag(int x, int val) {
for (int i = 0; i < B; ++i) t[x].mn[i] += val;
t[x].tag += val;
}
void modify(int x, int l, int r, int ql, int qr, int v) {
if (ql <= l && r <= qr) {
tag(x, v);
return;
}
int mid = (l + r) >> 1;
if (ql <= mid) modify(x << 1, l, mid, ql, qr, v);
if (qr > mid) modify(x << 1 | 1, mid + 1, r, ql, qr, v);
up(x);
}
void assign(int x, int l, int r, int p, const ll *v, int tag = 0) {
if (l == r) {
for (int i = 0; i < B; ++i) t[x].mn[i] = v[i] - tag;
return;
}
int mid = (l + r) >> 1;
tag += t[x].tag;
p <= mid ? assign(x << 1, l, mid, p, v, tag)
: assign(x << 1 | 1, mid + 1, r, p, v, tag);
up(x);
}
void build(int x, int l, int r) {
memset(t[x].mn, 0x3f, sizeof(t[x].mn));
if (l == 0) t[x].mn[0] = 0;
t[x].tag = 0;
if (l == r) return;
int mid = (l + r) >> 1;
build(x << 1, l, mid);
build(x << 1 | 1, mid + 1, r);
}
ll dp[N][B];
vector<int> di[N];
void prework(int n) {
sieve(n);
for (int i = 1; i <= n; ++i)
for (int j = i; j <= n; j += i) di[j].push_back(i);
build(1, 0, n);
for (int i = 1; i <= n; ++i) {
for (int d : di[i]) modify(1, 0, n, 0, d - 1, phi[i / d]);
dp[i][0] = INF;
for (int j = 0; j < B - 1; ++j) dp[i][j + 1] = t[1].mn[j];
assign(1, 0, n, i, dp[i]);
}
}
int main() {
int qc;
read(qc);
prework(100000);
while (qc--) {
int n, k;
read(n, k);
if (k >= B)
printf("%d\n", n);
else
printf("%lld\n", dp[n][k]);
}
return 0;
}
|
A sequence of integers b_1, b_2, …, b_m is called good if max(b_1, b_2, …, b_m) ⋅ min(b_1, b_2, …, b_m) ≥ b_1 + b_2 + … + b_m.
A sequence of integers a_1, a_2, …, a_n is called perfect if every non-empty subsequence of a is good.
YouKn0wWho has two integers n and M, M is prime. Help him find the number, modulo M, of perfect sequences a_1, a_2, …, a_n such that 1 ≤ a_i ≤ n + 1 for each integer i from 1 to n.
A sequence d is a subsequence of a sequence c if d can be obtained from c by deletion of several (possibly, zero or all) elements.
Input
The first and only line of the input contains two space-separated integers n and M (1 ≤ n ≤ 200; 10^8 ≤ M ≤ 10^9). It is guaranteed that M is prime.
Output
Print a single integer — the number of perfect sequences modulo M.
Examples
Input
2 998244353
Output
4
Input
4 100000007
Output
32
Input
69 999999937
Output
456886663
Note
In the first test case, the perfect sequences are [2, 2], [2, 3], [3, 2] and [3, 3].
In the second test case, some of the perfect sequences are [3, 4, 3, 5], [4, 5, 4, 4], [4, 5, 5, 5] etc. One example of a sequence which is not perfect is [2, 3, 3, 4], because, for example, the subsequence [2, 3, 4] is not an good as 2 ⋅ 4 < 2 + 3 + 4. | #include <bits/stdc++.h>
template <typename _Tp>
void read(_Tp &x) {
char ch(getchar());
bool f(false);
while (!isdigit(ch)) f |= ch == 45, ch = getchar();
x = ch & 15, ch = getchar();
while (isdigit(ch)) x = x * 10 + (ch & 15), ch = getchar();
if (f) x = -x;
}
template <typename _Tp, typename... Args>
void read(_Tp &t, Args &...args) {
read(t);
read(args...);
}
const int N = 205;
int n, mod;
template <typename _Tp1, typename _Tp2>
inline void add(_Tp1 &a, _Tp2 b) {
a = a + b >= mod ? a + b - mod : a + b;
}
template <typename _Tp1, typename _Tp2>
inline void sub(_Tp1 &a, _Tp2 b) {
a = a - b < 0 ? a - b + mod : a - b;
}
long long fac[N], inv[N], ifac[N];
void init() {
fac[0] = fac[1] = inv[0] = inv[1] = ifac[0] = ifac[1] = 1;
for (int i = 2; i < N; ++i)
fac[i] = fac[i - 1] * i % mod,
inv[i] = inv[mod % i] * (mod - mod / i) % mod,
ifac[i] = ifac[i - 1] * inv[i] % mod;
}
int dp[35][N][N];
int solve(int a1) {
memset(dp, 0, sizeof(dp)), dp[n + 2 - a1][0][0] = 1;
for (int i = n + 1 - a1, t = 0; i >= 1; --i, ++t) {
for (int j = 0; j <= n; ++j) {
for (int k = 0; k <= n; ++k)
if (dp[i + 1][j][k]) {
for (int c = 0; c * i + k <= a1 && c + j <= n; ++c) {
add(dp[i][j + c][k + c * i], 1LL * dp[i + 1][j][k] * ifac[c] % mod);
}
}
}
if (i > 1)
for (int j = 0; j <= t; ++j) memset(dp[i][j], 0, (n + 3) << 2);
}
int ans = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j <= a1; ++j)
add(ans, 1LL * dp[1][i][j] * ifac[n - i] % mod);
return fac[n] * ans % mod;
}
int main() {
read(n, mod);
init();
int ans = 1;
for (int x = std::max(1, n - 30); x <= n; ++x) add(ans, solve(x));
printf("%d\n", ans);
return 0;
}
|
It was October 18, 2017. Shohag, a melancholic soul, made a strong determination that he will pursue Competitive Programming seriously, by heart, because he found it fascinating. Fast forward to 4 years, he is happy that he took this road. He is now creating a contest on Codeforces. He found an astounding problem but has no idea how to solve this. Help him to solve the final problem of the round.
You are given three integers n, k and x. Find the number, modulo 998 244 353, of integer sequences a_1, a_2, …, a_n such that the following conditions are satisfied:
* 0 ≤ a_i < 2^k for each integer i from 1 to n.
* There is no non-empty subsequence in a such that the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of the elements of the subsequence is x.
A sequence b is a subsequence of a sequence c if b can be obtained from c by deletion of several (possibly, zero or all) elements.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The first and only line of each test case contains three space-separated integers n, k, and x (1 ≤ n ≤ 10^9, 0 ≤ k ≤ 10^7, 0 ≤ x < 2^{\operatorname{min}(20, k)}).
It is guaranteed that the sum of k over all test cases does not exceed 5 ⋅ 10^7.
Output
For each test case, print a single integer — the answer to the problem.
Example
Input
6
2 2 0
2 1 1
3 2 3
69 69 69
2017 10 18
5 7 0
Output
6
1
15
699496932
892852568
713939942
Note
In the first test case, the valid sequences are [1, 2], [1, 3], [2, 1], [2, 3], [3, 1] and [3, 2].
In the second test case, the only valid sequence is [0, 0]. | #include <bits/stdc++.h>
const long long MOD = 998244353;
int T, n, k, x, pow2[10000005], pw[10000005], ans;
int power(int A, int B) {
int res = 1;
while (B) {
if (B & 1) res = 1ll * res * A % MOD;
B >>= 1;
A = 1ll * A * A % MOD;
}
return res;
}
signed main() {
std::ios::sync_with_stdio(false);
pow2[0] = pw[0] = 1;
for (int i = 1; i <= 10000000; ++i) pow2[i] = pow2[i - 1] * 2 % MOD;
std::cin >> T;
while (T--) {
std::cin >> n >> k >> x;
if (x == 0) {
ans = 1;
if (n > k)
ans = 0;
else
for (int i = 0; i != n; ++i)
ans = ans * (pow2[k] - pow2[i] + MOD) % MOD;
std::cout << ans << std::endl;
} else {
ans = 0;
pw[1] = power(2, n);
for (int i = 1; i <= k; ++i) pw[i] = 1ll * pw[i - 1] * pw[1] % MOD;
for (int i = 1, sum = 1; i <= k; ++i) {
ans = (ans + (i & 1 ? 1 : MOD - 1) * pw[k - i] % MOD * sum % MOD *
pow2[k - i]) %
MOD;
sum = sum * (pow2[k - i] - 1ll) % MOD;
}
std::cout << ans << std::endl;
}
}
return 0;
}
|
Shohag has an integer sequence a_1, a_2, …, a_n. He can perform the following operation any number of times (possibly, zero):
* Select any positive integer k (it can be different in different operations).
* Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert k into the sequence at this position.
* This way, the sequence a changes, and the next operation is performed on this changed sequence.
For example, if a=[3,3,4] and he selects k = 2, then after the operation he can obtain one of the sequences [\underline{2},3,3,4], [3,\underline{2},3,4], [3,3,\underline{2},4], or [3,3,4,\underline{2}].
Shohag wants this sequence to satisfy the following condition: for each 1 ≤ i ≤ |a|, a_i ≤ i. Here, |a| denotes the size of a.
Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.
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 a single integer n (1 ≤ n ≤ 100) — the initial length of the sequence.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the sequence.
Output
For each test case, print a single integer — the minimum number of operations needed to perform to achieve the goal mentioned in the statement.
Example
Input
4
3
1 3 4
5
1 2 5 7 4
1
1
3
69 6969 696969
Output
1
3
0
696966
Note
In the first test case, we have to perform at least one operation, as a_2=3>2. We can perform the operation [1, 3, 4] → [1, \underline{2}, 3, 4] (the newly inserted element is underlined), now the condition is satisfied.
In the second test case, Shohag can perform the following operations:
[1, 2, 5, 7, 4] → [1, 2, \underline{3}, 5, 7, 4] → [1, 2, 3, \underline{4}, 5, 7, 4] → [1, 2, 3, 4, 5, \underline{3}, 7, 4].
In the third test case, the sequence already satisfies the condition. | import java.lang.Math;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class codeforces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int a= sc.nextInt();
int b[]=new int[a];
for(int i=0;i<a;i++)
{
b[i]=sc.nextInt();
}
int count=0;
int res=0;
for(int i=0;i<a;i++)
{
if(b[i]>(i+1+res))
{
count+=b[i]-(i+1+res);
res=b[i]-(i+1);
}
}
System.out.println(count);
}
}
}
|
YouKn0wWho has an integer sequence a_1, a_2, … a_n. Now he will split the sequence a into one or more consecutive subarrays so that each element of a belongs to exactly one subarray. Let k be the number of resulting subarrays, and h_1, h_2, …, h_k be the lengths of the longest increasing subsequences of corresponding subarrays.
For example, if we split [2, 5, 3, 1, 4, 3, 2, 2, 5, 1] into [2, 5, 3, 1, 4], [3, 2, 2, 5], [1], then h = [3, 2, 1].
YouKn0wWho wonders if it is possible to split the sequence a in such a way that the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of h_1, h_2, …, h_k is equal to 0. You have to tell whether it is possible.
The longest increasing subsequence (LIS) of a sequence b_1, b_2, …, b_m is the longest sequence of valid indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and b_{i_1} < b_{i_2} < … < b_{i_k}. For example, the LIS of [2, 5, 3, 3, 5] is [2, 3, 5], which has length 3.
An array c is a subarray of an array b if c 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.
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^9).
It is guaranteed that the sum of n over all test cases doesn't exceed 3 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if it is possible to split into subarrays in the desired way, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).
Example
Input
4
7
1 3 4 2 2 1 5
3
1 3 4
5
1 3 2 4 2
4
4 3 2 1
Output
YES
NO
YES
YES
Note
In the first test case, YouKn0wWho can split the sequence in the following way: [1, 3, 4], [2, 2], [1, 5]. This way, the LIS lengths are h = [3, 1, 2], and the bitwise XOR of the LIS lengths is 3 ⊕ 1 ⊕ 2 = 0.
In the second test case, it can be shown that it is impossible to split the sequence into subarrays that will satisfy the condition. | #include <bits/stdc++.h>
using namespace std;
void solve() {
long long n;
cin >> n;
vector<long long> a(n);
for (long long i = 0; i < n; ++i) cin >> a[i];
bool sorted = true;
for (long long i = 1; i < n; ++i) {
if (a[i] <= a[i - 1]) sorted = false;
}
if (sorted and n % 2) {
cout << "NO";
} else {
cout << "YES";
}
cout << endl;
}
int32_t main() {
long long t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
YouKn0wWho has an integer sequence a_1, a_2, …, a_n. He will perform the following operation until the sequence becomes empty: select an index i such that 1 ≤ i ≤ |a| and a_i is not divisible by (i + 1), and erase this element from the sequence. Here |a| is the length of sequence a at the moment of operation. Note that the sequence a changes and the next operation is performed on this changed sequence.
For example, if a=[3,5,4,5], then he can select i = 2, because a_2 = 5 is not divisible by i+1 = 3. After this operation the sequence is [3,4,5].
Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.
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 (1 ≤ n ≤ 10^5).
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases doesn't exceed 3 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).
Example
Input
5
3
1 2 3
1
2
2
7 7
10
384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328
8
6 69 696 69696 696969 6969696 69696969 696969696
Output
YES
NO
YES
YES
NO
Note
In the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): [1, \underline{2}, 3] → [\underline{1}, 3] → [\underline{3}] → [ ].
In the second test case, it is impossible to erase the sequence as i can only be 1, and when i=1, a_1 = 2 is divisible by i + 1 = 2. | import java.util.Scanner;
public class Hello {
public static void main(String[] args){
Scanner r = new Scanner(System.in);
int test = r.nextInt();
while(test-->0){
int n = r.nextInt();
String ans = "YES";
boolean f = true;
me2: for(int i=0;i<n;i++){
int num1 = r.nextInt();
int limit = i+2;
boolean flag = true;
if(f){
me1: for(int j=limit;j>1;j--){
if(num1%j != 0){
flag = false;
break me1;
}
}
if(flag){
ans = "NO";
f = false;
}
}
}
System.out.println(ans);
}
}
}
|
YouKn0wWho has two even integers x and y. Help him to find an integer n such that 1 ≤ n ≤ 2 ⋅ 10^{18} and n mod x = y mod n. Here, a mod b denotes the remainder of a after division by b. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The first and only line of each test case contains two integers x and y (2 ≤ x, y ≤ 10^9, both are even).
Output
For each test case, print a single integer n (1 ≤ n ≤ 2 ⋅ 10^{18}) that satisfies the condition mentioned in the statement. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.
Example
Input
4
4 8
4 2
420 420
69420 42068
Output
4
10
420
9969128
Note
In the first test case, 4 mod 4 = 8 mod 4 = 0.
In the second test case, 10 mod 4 = 2 mod 10 = 2.
In the third test case, 420 mod 420 = 420 mod 420 = 0. | #include <bits/stdc++.h>
using namespace std;
int main() {
int _TC_;
cin >> _TC_;
while (_TC_--) {
int x, y;
cin >> x >> y;
if (x > y) {
cout << x + y << endl;
continue;
}
cout << (y + (y / x * x)) / 2 << endl;
}
}
|
For an array b of n integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make b non-decreasing:
* Select an index i such that 1 ≤ i ≤ |b|, where |b| is the current length of b.
* Replace b_i with two elements x and y such that x and y both are positive integers and x + y = b_i.
* This way, the array b changes and the next operation is performed on this modified array.
For example, if b = [2, 4, 3] and index 2 gets selected, then the possible arrays after this operation are [2, \underline{1}, \underline{3}, 3], [2, \underline{2}, \underline{2}, 3], or [2, \underline{3}, \underline{1}, 3]. And consequently, for this array, this single operation is enough to make it non-decreasing: [2, 4, 3] → [2, \underline{2}, \underline{2}, 3].
It's easy to see that every array of positive integers can be made non-decreasing this way.
YouKn0wWho has an array a of n integers. Help him find the sum of extreme values of all nonempty subarrays of a modulo 998 244 353. If a subarray appears in a multiple times, its extreme value should be counted the number of times it appears.
An array d is a subarray of an array c if d can be obtained from c by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
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 (1 ≤ n ≤ 10^5).
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^5).
It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.
Output
For each test case, print a single integer — the sum of extreme values of all subarrays of a modulo 998 244 353.
Example
Input
4
3
5 4 3
4
3 2 1 4
1
69
8
7264 40515 28226 92776 35285 21709 75124 48163
Output
5
9
0
117
Note
Let f(l, r) denote the extreme value of [a_l, a_{l+1}, …, a_r].
In the first test case,
* f(1, 3) = 3, because YouKn0wWho can perform the following operations on the subarray [5, 4, 3] (the newly inserted elements are underlined):
[5, 4, 3] → [\underline{3}, \underline{2}, 4, 3] → [3, 2, \underline{2}, \underline{2}, 3] → [\underline{1}, \underline{2}, 2, 2, 2, 3];
* f(1, 2) = 1, because [5, 4] → [\underline{2}, \underline{3}, 4];
* f(2, 3) = 1, because [4, 3] → [\underline{1}, \underline{3}, 3];
* f(1, 1) = f(2, 2) = f(3, 3) = 0, because they are already non-decreasing.
So the total sum of extreme values of all subarrays of a = 3 + 1 + 1 + 0 + 0 + 0 = 5. | #include <bits/stdc++.h>
using namespace std;
const long long maxl = 2e5 + 7;
const long long mod = 998244353;
vector<long long> v[2];
long long dp[2][maxl];
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
long long n;
cin >> n;
long long ans = 0;
vector<long long> nana(n + 10);
for (long long i = 1; i <= n; i++) cin >> nana[i];
for (long long i = n; i >= 1; i--) {
long long k = i & 1;
v[k].push_back(nana[i]);
dp[k][nana[i]] = 1;
long long las = nana[i];
for (auto& x : v[k ^ 1]) {
long long chuxiancishu = dp[k ^ 1][x];
long long fenkuai = (nana[i] + x - 1) / x;
long long newx = nana[i] / fenkuai;
ans += chuxiancishu * i % mod * (fenkuai - 1) % mod;
dp[k][newx] += chuxiancishu;
if (las != newx) v[k].push_back(newx), las = newx;
}
for (auto& x : v[k ^ 1]) dp[k ^ 1][x] = 0;
v[k ^ 1].clear();
ans %= mod;
}
cout << ans << '\n';
for (auto& x : v[0]) dp[0][x] = 0;
for (auto& x : v[1]) dp[1][x] = 0;
v[0].clear(), v[1].clear();
}
}
|
You are given a string s of length n consisting of characters a and/or b.
Let \operatorname{AB}(s) be the number of occurrences of string ab in s as a substring. Analogically, \operatorname{BA}(s) is the number of occurrences of ba in s as a substring.
In one step, you can choose any index i and replace s_i with character a or b.
What is the minimum number of steps you need to make to achieve \operatorname{AB}(s) = \operatorname{BA}(s)?
Reminder:
The number of occurrences of string d in s as substring is the number of indices i (1 ≤ i ≤ |s| - |d| + 1) such that substring s_i s_{i + 1} ... s_{i + |d| - 1} is equal to d. For example, \operatorname{AB}(aabbbabaa) = 2 since there are two indices i: i = 2 where aabbbabaa and i = 6 where aabbbabaa.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000). Description of the test cases follows.
The first and only line of each test case contains a single string s (1 ≤ |s| ≤ 100, where |s| is the length of the string s), consisting only of characters a and/or b.
Output
For each test case, print the resulting string s with \operatorname{AB}(s) = \operatorname{BA}(s) you'll get making the minimum number of steps.
If there are multiple answers, print any of them.
Example
Input
4
b
aabbbabaa
abbb
abbaab
Output
b
aabbbabaa
bbbb
abbaaa
Note
In the first test case, both \operatorname{AB}(s) = 0 and \operatorname{BA}(s) = 0 (there are no occurrences of ab (ba) in b), so can leave s untouched.
In the second test case, \operatorname{AB}(s) = 2 and \operatorname{BA}(s) = 2, so you can leave s untouched.
In the third test case, \operatorname{AB}(s) = 1 and \operatorname{BA}(s) = 0. For example, we can change s_1 to b and make both values zero.
In the fourth test case, \operatorname{AB}(s) = 2 and \operatorname{BA}(s) = 1. For example, we can change s_6 to a and make both values equal to 1. | #include <bits/stdc++.h>
using namespace std;
template <typename t1, typename t2>
using umap = unordered_map<t1, t2>;
template <typename t>
using uset = unordered_set<t>;
struct pair_hash {
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2>& p) const {
auto h1 = std::hash<T1>{}(p.first);
auto h2 = std::hash<T2>{}(p.second);
return h1 ^ h2;
}
};
template <class Container>
void split3(const std::string& str, Container& cont, char delim = ' ') {
std::size_t current, previous = 0;
current = str.find(delim);
while (current != std::string::npos) {
cont.push_back(str.substr(previous, current - previous));
previous = current + 1;
current = str.find(delim, previous);
}
cont.push_back(str.substr(previous, current - previous));
}
long long gcd(long long a, long long b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
void zf(string& s, vector<long long>& z) {
long long l = 0, r = 0;
for (long long i = 1; i < s.size(); i++) {
if (r >= i) {
z[i] = min(z[i - l], r - i + 1);
}
while (z[i] + i < s.size() && s[z[i]] == s[z[i] + i]) {
z[i]++;
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
}
vector<long long> zf(string& a, string& b, string delimiter = "$") {
string s = b + delimiter + a;
vector<long long> z(s.size(), 0);
long long l = 0, r = 0;
for (long long i = 1; i < s.size(); i++) {
if (r >= i) {
z[i] = min(z[i - l], r - i + 1);
}
while (z[i] + i < s.size() && s[z[i]] == s[z[i] + i]) {
z[i]++;
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
const long long INF = 1e9 + 1;
const long long MOD = 1e9 + 7;
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
long long t;
cin >> t;
cin.ignore();
for (long long _ = 0; _ < t; _++) {
string s;
getline(cin, s);
long long ab = 0, ba = 0;
for (long long i = 0; i < s.size() - 1; i++) {
if (s[i] == 'a' && s[i + 1] == 'b') {
ab++;
}
if (s[i] == 'b' && s[i + 1] == 'a') {
ba++;
}
}
if (ba == ab) {
cout << s << "\n";
} else if (ba > ab) {
cout << 'a' << s.substr(1) << "\n";
} else {
cout << 'b' << s.substr(1) << "\n";
}
}
return 0;
}
|
Berland State University has received a new update for the operating system. Initially it is installed only on the 1-st computer.
Update files should be copied to all n computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.
Your task is to find the minimum number of hours required to copy the update files to all n computers if there are only k patch cables in Berland State University.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
Each test case consists of a single line that contains two integers n and k (1 ≤ k ≤ n ≤ 10^{18}) — the number of computers and the number of patch cables.
Output
For each test case print one integer — the minimum number of hours required to copy the update files to all n computers.
Example
Input
4
8 3
6 6
7 1
1 1
Output
4
3
6
0
Note
Let's consider the test cases of the example:
* n=8, k=3:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4;
3. during the third hour, we copy the update files from the computer 1 to the computer 5, from the computer 2 to the computer 6, and from the computer 3 to the computer 7;
4. during the fourth hour, we copy the update files from the computer 2 to the computer 8.
* n=6, k=6:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3, and from the computer 2 to the computer 4;
3. during the third hour, we copy the update files from the computer 1 to the computer 5, and from the computer 2 to the computer 6.
* n=7, k=1:
1. during the first hour, we copy the update files from the computer 1 to the computer 2;
2. during the second hour, we copy the update files from the computer 1 to the computer 3;
3. during the third hour, we copy the update files from the computer 1 to the computer 4;
4. during the fourth hour, we copy the update files from the computer 4 to the computer 5;
5. during the fifth hour, we copy the update files from the computer 4 to the computer 6;
6. during the sixth hour, we copy the update files from the computer 3 to the computer 7. | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
// Sachin_2961 submission //
public class Codeforces {
static void solve(){
long n = fs.nLong(), k = fs.nLong();
long ans = 0,cur = 1L;
while( cur < k ){
cur *= 2L;
ans++;
}
if( cur < n ){
ans += (n-cur+k-1)/k;
}
out.println(ans);
}
static class Pair{
int value,ind;
Pair(int value,int ind){
this.value = value;
this.ind = ind;
}
}
static boolean multipleTestCase = true;
static FastScanner fs;
static PrintWriter out;
public static void main(String[]args){
try{
out = new PrintWriter(System.out);
fs = new FastScanner();
int tc = multipleTestCase?fs.nInt():1;
while (tc-->0)solve();
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String n() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String Line()
{
String str = "";
try
{
str = br.readLine();
}catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int nInt() {return Integer.parseInt(n()); }
long nLong() {return Long.parseLong(n());}
double nDouble(){return Double.parseDouble(n());}
int[]aI(int n){
int[]ar = new int[n];
for(int i=0;i<n;i++)
ar[i] = nInt();
return ar;
}
}
public static void sort(int[] arr){
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sort(long[] arr){
ArrayList<Long> ls = new ArrayList<>();
for(long x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
} |
In Berland, n different types of banknotes are used. Banknotes of the i-th type have denomination 10^{a_i} burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly 1.
Let's denote f(s) as the minimum number of banknotes required to represent exactly s burles. For example, if the denominations of banknotes used in Berland are 1, 10 and 100, then f(59) = 14: 9 banknotes with denomination of 1 burle and 5 banknotes with denomination of 10 burles can be used to represent exactly 9 ⋅ 1 + 5 ⋅ 10 = 59 burles, and there's no way to do it with fewer banknotes.
For a given integer k, find the minimum positive number of burles s that cannot be represented with k or fewer banknotes (that is, f(s) > k).
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 10; 1 ≤ k ≤ 10^9).
The next line contains n integers a_1, a_2, ..., a_n (0 = a_1 < a_2 < ... < a_n ≤ 9).
Output
For each test case, print one integer — the minimum positive number of burles s that cannot be represented with k or fewer banknotes.
Example
Input
4
3 13
0 1 2
2 777
0 4
3 255
0 1 3
10 1000000000
0 1 2 3 4 5 6 7 8 9
Output
59
778
148999
999999920999999999 | for _ in range(int(input())):
n,k = list(map(int,input().split(" ")))
ls = list(map(int,input().split(" ")))
p10s = [10**i for i in ls]
ans = 0
used = 0
kk = k
last = 1
for i,j in zip(p10s,p10s[1:]):
if kk*i == j-1:
ans += j + (kk-1)*i
kk = 0
break
if kk*i >= j:
ans += (j-1)-(i-1) - (1 if i==1 else 0)
used += (j//i)-1 - (1 if i==1 else 0)
kk = k-used
last = j
else:
ans += kk*i
kk = 0
break
if kk>0:
ans += kk*last
print(ans+1)
|
You are given a matrix, consisting of n rows and m columns. The j-th cell of the i-th row contains an integer a_{ij}.
First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.
Then, you have to choose an integer k (1 ≤ k < m) and cut the colored matrix in such a way that the first k columns become a separate matrix (the left matrix) and the last m-k columns become a separate matrix (the right matrix).
The coloring and the cut are called perfect if two properties hold:
* every red cell in the left matrix contains an integer greater than every blue cell in the left matrix;
* every blue cell in the right matrix contains an integer greater than every red cell in the right matrix.
Find any perfect coloring and cut, or report that there are none.
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 each testcase contains two integers n and m (2 ≤ n, m ≤ 5 ⋅ 10^5; n ⋅ m ≤ 10^6) — the number of rows and the number of columns in the matrix, respectively.
The i-th of the next n lines contains m integers a_{i1}, a_{i2}, ..., a_{im} (1 ≤ a_{ij} ≤ 10^6).
The sum of n ⋅ m over all testcases doesn't exceed 10^6.
Output
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO".
Otherwise, first, print "YES". Then a string, consisting of n characters: the i-th character should be 'R' if the i-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer k (1 ≤ k < m) — the number of columns from the left that are cut.
Example
Input
3
5 5
1 5 8 8 7
5 2 1 4 3
1 6 9 7 5
9 3 3 3 2
1 7 9 9 8
3 3
8 9 8
1 5 3
7 5 7
2 6
3 3 3 2 2 2
1 1 1 4 4 4
Output
YES
BRBRB 1
NO
YES
RB 3
Note
The coloring and the cut for the first testcase:
<image> | #include <bits/stdc++.h>
using namespace std;
template <class T>
bool uin(T &a, T b) {
return a > b ? (a = b, true) : false;
}
template <class T>
bool uax(T &a, T b) {
return a < b ? (a = b, true) : false;
}
mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
const int maxN = 1e5 + 10;
int n, m;
void solve() {
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m));
vector<vector<int>> pre_min(n, vector<int>(m));
vector<vector<int>> pre_max(n, vector<int>(m));
vector<vector<int>> suf_min(n, vector<int>(m));
vector<vector<int>> suf_max(n, vector<int>(m));
for (int i = 0; i < (int)(n); ++i) {
for (int j = 0; j < (int)(m); ++j) {
cin >> a[i][j];
}
}
for (int i = 0; i < (int)(n); ++i) {
pre_min[i][0] = pre_max[i][0] = a[i][0];
for (int j = 1; j <= (int)(m - 1); ++j) {
pre_min[i][j] = min(pre_min[i][j - 1], a[i][j]);
pre_max[i][j] = max(pre_max[i][j - 1], a[i][j]);
}
suf_min[i][m - 1] = suf_max[i][m - 1] = a[i][m - 1];
for (int j = (int)(m - 1) - 1; j >= 0; --j) {
suf_min[i][j] = min(suf_min[i][j + 1], a[i][j]);
suf_max[i][j] = max(suf_max[i][j + 1], a[i][j]);
}
}
for (int col = 0; col < (int)(m - 1); ++col) {
vector<int> vec(n);
iota((vec).begin(), (vec).end(), 0);
sort((vec).begin(), (vec).end(),
[&](int i, int j) { return pre_max[i][col] < pre_max[j][col]; });
vector<int> suf_x(n), suf_y(n);
suf_x[n - 1] = pre_min[vec[n - 1]][col];
suf_y[n - 1] = suf_max[vec[n - 1]][col + 1];
for (int i = (int)(n - 1) - 1; i >= 0; --i) {
suf_x[i] = min(suf_x[i + 1], pre_min[vec[i]][col]);
suf_y[i] = max(suf_y[i + 1], suf_max[vec[i]][col + 1]);
}
int x = pre_max[vec[0]][col], y = suf_min[vec[0]][col + 1];
int pos = -1;
for (int i = 0; i < (int)(n - 1); ++i) {
if (x < suf_x[i + 1] && y > suf_y[i + 1]) {
pos = i;
break;
}
x = max(x, pre_max[vec[i + 1]][col]);
y = min(y, suf_min[vec[i + 1]][col + 1]);
}
if (pos != -1) {
string ans(n, 0);
for (int i = 0; i < (int)(n); ++i) {
if (i <= pos) {
ans[vec[i]] = 'B';
} else {
ans[vec[i]] = 'R';
}
}
cout << "YES\n" << ans << " " << col + 1 << "\n";
return;
}
}
cout << "NO\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
}
|
There are n heroes fighting in the arena. Initially, the i-th hero has a_i health points.
The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals 1 damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than 1 at the end of the round are considered killed.
If exactly 1 hero remains alive after a certain round, then he is declared the winner. Otherwise, there is no winner.
Your task is to calculate the number of ways to choose the initial health points for each hero a_i, where 1 ≤ a_i ≤ x, so that there is no winner of the fight. The number of ways can be very large, so print it modulo 998244353. Two ways are considered different if at least one hero has a different amount of health. For example, [1, 2, 1] and [2, 1, 1] are different.
Input
The only line contains two integers n and x (2 ≤ n ≤ 500; 1 ≤ x ≤ 500).
Output
Print one integer — the number of ways to choose the initial health points for each hero a_i, where 1 ≤ a_i ≤ x, so that there is no winner of the fight, taken modulo 998244353.
Examples
Input
2 5
Output
5
Input
3 3
Output
15
Input
5 4
Output
1024
Input
13 37
Output
976890680 | #include <bits/stdc++.h>
using namespace std;
int n, x;
int f[505][505], C[505][505], pw[505][505];
void add(int &a, int b) {
a += b;
if (a >= 998244353) a -= 998244353;
}
void init() {
for (int i = 0; i <= 500; i++) C[0][i] = 1;
for (int i = 1; i <= 500; i++)
for (int j = i; j <= 500; j++)
C[i][j] = (C[i - 1][j - 1] + C[i][j - 1]) % 998244353;
for (int i = 1; i <= 500; i++) {
pw[i][0] = 1;
for (int j = 1; j <= 500; j++)
pw[i][j] = (1ll * pw[i][j - 1] * i) % 998244353;
}
}
void solve() {
cin >> n >> x;
init();
for (int i = 0; i <= 0; i++) f[n][i] = 1;
for (int i = n; i > 1; i--)
for (int j = 0; j <= x; j++) {
if (!f[i][j]) continue;
for (int k = 0; k <= i; k++) {
int h = min(x, j + i - 1);
add(f[k][h], 1ll * C[i - k][i] * pw[h - j][i - k] % 998244353 *
f[i][j] % 998244353);
}
}
int res = 0;
for (int i = 0; i <= x; i++) add(res, f[0][i]);
cout << res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long T = 1;
for (int i = 1; i <= T; i++) {
solve();
}
return 0;
}
|
You are given a tree consisting of n vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex 1.
You have to process q queries. In each query, you are given a vertex of the tree v and an integer k.
To process a query, you may delete any vertices from the tree in any order, except for the root and the vertex v. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of c(v) - m ⋅ k (where c(v) is the resulting number of children of the vertex v, and m is the number of vertices you have deleted). Print the maximum possible value you can obtain.
The queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Then n-1 lines follow, the i-th of them contains two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) — the endpoints of the i-th edge. These edges form a tree.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, the j-th of them contains two integers v_j and k_j (1 ≤ v_j ≤ n; 0 ≤ k_j ≤ 2 ⋅ 10^5) — the parameters of the j-th query.
Output
For each query, print one integer — the maximum value of c(v) - m ⋅ k you can achieve.
Example
Input
8
6 7
3 2
8 3
5 7
7 4
7 1
7 3
6
1 0
1 2
1 3
7 1
5 0
7 200000
Output
5
2
1
4
0
4
Note
The tree in the first example is shown in the following picture:
<image>
Answers to the queries are obtained as follows:
1. v=1,k=0: you can delete vertices 7 and 3, so the vertex 1 has 5 children (vertices 2, 4, 5, 6, and 8), and the score is 5 - 2 ⋅ 0 = 5;
2. v=1,k=2: you can delete the vertex 7, so the vertex 1 has 4 children (vertices 3, 4, 5, and 6), and the score is 4 - 1 ⋅ 2 = 2.
3. v=1,k=3: you shouldn't delete any vertices, so the vertex 1 has only one child (vertex 7), and the score is 1 - 0 ⋅ 3 = 1;
4. v=7,k=1: you can delete the vertex 3, so the vertex 7 has 5 children (vertices 2, 4, 5, 6, and 8), and the score is 5 - 1 ⋅ 1 = 4;
5. v=5,k=0: no matter what you do, the vertex 5 will have no children, so the score is 0;
6. v=7,k=200000: you shouldn't delete any vertices, so the vertex 7 has 4 children (vertices 3, 4, 5, and 6), and the score is 4 - 0 ⋅ 200000 = 4. | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
using namespace std;
const long long N = 2e5 + 11;
const long long M = 1e6 + 21;
const long long big = 1e17;
const long long hsh2 = 1964325029;
const long long mod = 1e9 + 7;
const double EPS = 1e-9;
const long long block = 100;
const long long shift = 2e3;
const double pi = acos(-1.0);
mt19937_64 bruh(chrono::steady_clock::now().time_since_epoch().count());
long long n, k;
long long x[N], y[N];
long long q, answ[N];
vector<long long> g[N], ng[N], bg[N];
vector<pair<long long, long long> > que[N];
long long dp[N], sum[N];
long long potential[N], sub[N];
long long tin[N], arr[N];
void prec(long long v, long long p = 0) {
tin[v] = ++tin[0];
arr[tin[v]] = v;
for (auto u : g[v])
if (u != p) prec(u, v), bg[v].push_back(u);
}
void calc_potentials(long long v, long long p) {
potential[v] = 1;
long long second = 0;
for (auto u : g[v]) {
if (u != p) calc_potentials(u, v), second += potential[u];
}
potential[v] = max(1ll, second - block);
}
void build(long long v, long long p) {
for (auto u : g[v]) {
if (u == p) continue;
if (potential[u] >= block)
ng[v].push_back(u);
else
sub[v]++;
build(u, v);
}
}
void naive(long long v) {
long long answ = sub[v];
dp[v] = 1;
sum[v] = sub[v];
for (auto u : ng[v]) {
naive(u);
sum[v] += dp[u];
}
dp[v] = max(1ll, sum[v] - k);
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
long long a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
cin >> q;
for (int i = 1; i <= q; i++) {
long long v, k;
cin >> v >> k;
que[k].push_back(make_pair(v, i));
}
prec(1, 0);
for (int j = 0; j <= 500; j++) {
k = j;
for (int j = n; j >= 1; j--) {
long long v = arr[j];
dp[v] = 0;
sum[v] = 0;
for (auto u : bg[v]) sum[v] += dp[u];
dp[v] = max(1ll, sum[v] - k);
}
for (auto u : que[j]) answ[u.second] = sum[u.first];
}
calc_potentials(1, 0);
build(1, 0);
for (int j = 501; j <= 200000; j++) {
for (auto u : que[j]) {
k = j;
naive(u.first);
answ[u.second] = sum[u.first];
}
}
for (int i = 1; i <= q; i++) cout << answ[i] << '\n';
}
|
You are given a keyboard that consists of 26 keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.
You have to type the word s on this keyboard. It also consists only of lowercase Latin letters.
To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.
Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.
For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions 8, 5, 12 and 15, respectively. Therefore, it will take |5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13 units of time to type the word "hello".
Determine how long it will take to print the word s.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases.
The next 2t lines contain descriptions of the test cases.
The first line of a description contains a keyboard — a string of length 26, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard.
The second line of the description contains the word s. The word has a length from 1 to 50 letters inclusive and consists of lowercase Latin letters.
Output
Print t lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word s on the given keyboard.
Example
Input
5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba
Output
13
0
68
0
74 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
string wrd;
cin >> wrd;
int arr[200] = {};
for (int i = 0; i < s.size(); i++) {
arr[s[i]] = i;
}
int time = 0;
for (int i = 1; i < wrd.length(); i++) {
time += abs(arr[wrd[i]] - arr[wrd[i - 1]]);
}
cout << time << endl;
}
}
|
The grasshopper is located on the numeric axis at the point with coordinate x_0.
Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate x with a distance d to the left moves the grasshopper to a point with a coordinate x - d, while jumping to the right moves him to a point with a coordinate x + d.
The grasshopper is very fond of positive integers, so for each integer i starting with 1 the following holds: exactly i minutes after the start he makes a jump with a distance of exactly i. So, in the first minutes he jumps by 1, then by 2, and so on.
The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.
For example, if after 18 consecutive jumps he arrives at the point with a coordinate 7, he will jump by a distance of 19 to the right, since 7 is an odd number, and will end up at a point 7 + 19 = 26. Since 26 is an even number, the next jump the grasshopper will make to the left by a distance of 20, and it will move him to the point 26 - 20 = 6.
Find exactly which point the grasshopper will be at after exactly n jumps.
Input
The first line of input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Each of the following t lines contains two integers x_0 (-10^{14} ≤ x_0 ≤ 10^{14}) and n (0 ≤ n ≤ 10^{14}) — the coordinate of the grasshopper's initial position and the number of jumps.
Output
Print exactly t lines. On the i-th line print one integer — the answer to the i-th test case — the coordinate of the point the grasshopper will be at after making n jumps from the point x_0.
Example
Input
9
0 1
0 2
10 10
10 99
177 13
10000000000 987654321
-433494437 87178291199
1 0
-1 1
Output
-1
1
11
110
190
9012345679
-87611785637
1
0
Note
The first two test cases in the example correspond to the first two jumps from the point x_0 = 0.
Since 0 is an even number, the first jump of length 1 is made to the left, and the grasshopper ends up at the point 0 - 1 = -1.
Then, since -1 is an odd number, a jump of length 2 is made to the right, bringing the grasshopper to the point with coordinate -1 + 2 = 1. | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
long long n, x;
cin >> x >> n;
if (x & 1) {
if (n & 1) {
if ((n / 2) & 1)
x = x - n - 1;
else
x = x + n;
} else {
if (((n / 2) & 1)) x = x - 1;
}
} else {
if (n & 1) {
if ((n / 2) & 1)
x = x + n + 1;
else
x = x - n;
} else {
if ((n / 2) & 1) x = x + 1;
}
}
printf("%lld", x);
if (t) printf("\n");
}
}
|
Yelisey has an array a of n integers.
If a has length strictly greater than 1, then Yelisei can apply an operation called minimum extraction to it:
1. First, Yelisei finds the minimal number m in the array. If there are several identical minima, Yelisey can choose any of them.
2. Then the selected minimal element is removed from the array. After that, m is subtracted from each remaining element.
Thus, after each operation, the length of the array is reduced by 1.
For example, if a = [1, 6, -4, -2, -4], then the minimum element in it is a_3 = -4, which means that after this operation the array will be equal to a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0].
Since Yelisey likes big numbers, he wants the numbers in the array a to be as big as possible.
Formally speaking, he wants to make the minimum of the numbers in array a to be maximal possible (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length 1.
Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The next 2t lines contain descriptions of the test cases.
In the description of each test case, the first line contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the original length of the array a. The second line of the description lists n space-separated integers a_i (-10^9 ≤ a_i ≤ 10^9) — elements of the array a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Print t lines, each of them containing the answer to the corresponding test case. The answer to the test case is a single integer — the maximal possible minimum in a, which can be obtained by several applications of the described operation to it.
Example
Input
8
1
10
2
0 0
3
-1 2 0
4
2 10 1 7
2
2 3
5
3 2 -4 -2 0
2
-1 1
1
-2
Output
10
0
2
5
2
2
2
-2
Note
In the first example test case, the original length of the array n = 1. Therefore minimum extraction cannot be applied to it. Thus, the array remains unchanged and the answer is a_1 = 10.
In the second set of input data, the array will always consist only of zeros.
In the third set, the array will be changing as follows: [\color{blue}{-1}, 2, 0] → [3, \color{blue}{1}] → [\color{blue}{2}]. The minimum elements are highlighted with \color{blue}{blue}. The maximal one is 2.
In the fourth set, the array will be modified as [2, 10, \color{blue}{1}, 7] → [\color{blue}{1}, 9, 6] → [8, \color{blue}{5}] → [\color{blue}{3}]. Similarly, the maximum of the minimum elements is 5. | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> list;
int max_value = INT_MIN;
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
list.push_back(temp);
}
sort((list).begin(), (list).end());
int change = 0;
for (int i = 0; i < list.size(); i++) {
list[i] = list[i] - change;
max_value = max(list[i], max_value);
change += list[i];
}
cout << max_value << '\n';
;
}
return 0;
}
|
You are given an array of integers a of length n. The elements of the array can be either different or the same.
Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step:
* either you can select any blue element and decrease its value by 1;
* or you can select any red element and increase its value by 1.
Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.
Determine whether it is possible to make 0 or more steps such that the resulting array is a permutation of numbers from 1 to n?
In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array a contains in some order all numbers from 1 to n (inclusive), each exactly once.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of input data sets in the test.
The description of each set of input data consists of three lines. The first line contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the original array a. The second line contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the array elements themselves.
The third line has length n and consists exclusively of the letters 'B' and/or 'R': ith character is 'B' if a_i is colored blue, and is 'R' if colored red.
It is guaranteed that the sum of n over all input sets does not exceed 2 ⋅ 10^5.
Output
Print t lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise.
You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
Example
Input
8
4
1 2 5 2
BRBR
2
1 1
BB
5
3 1 4 2 5
RBRRB
5
3 1 3 1 3
RBRRB
5
5 1 5 1 5
RBRRB
4
2 2 2 2
BRBR
2
1 -2
BR
4
-2 -1 4 0
RRRR
Output
YES
NO
YES
YES
NO
YES
YES
YES
Note
In the first test case of the example, the following sequence of moves can be performed:
* choose i=3, element a_3=5 is blue, so we decrease it, we get a=[1,2,4,2];
* choose i=2, element a_2=2 is red, so we increase it, we get a=[1,3,4,2];
* choose i=3, element a_3=4 is blue, so we decrease it, we get a=[1,3,3,2];
* choose i=2, element a_2=2 is red, so we increase it, we get a=[1,4,3,2].
We got that a is a permutation. Hence the answer is YES. | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
pair<int, int> a[N];
char c[N];
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i].first);
scanf("%s", c + 1);
for (int i = 1; i <= n; i++) {
if (c[i] == 'R')
a[i].second = 1;
else
a[i].second = -1;
}
sort(a + 1, a + 1 + n);
int flag = 0;
int num = 0;
for (int i = n; i >= 1; i--) {
if (a[i].second == 1) {
num++;
if (a[i].first > n) flag = 1;
if (num > n - a[i].first + 1) flag = 1;
}
if (flag) break;
}
num = 0;
for (int i = 1; i <= n; i++) {
if (a[i].second == -1) {
num++;
if (a[i].first < 1) flag = 1;
if (num > a[i].first) flag = 1;
}
if (flag) break;
}
if (flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
|
The robot is located on a checkered rectangular board of size n × m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right.
The robot is able to move from the current cell to one of the four cells adjacent by side.
The sequence of commands s executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.
The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in s. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.
The robot's task is to execute as many commands as possible without falling off the board. For example, on board 3 × 3, if the robot starts a sequence of actions s="RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell (2, 1) (second row, first column) then all commands will be executed successfully and the robot will stop at the cell (1, 2) (first row, second column).
<image> The robot starts from cell (2, 1) (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell (1, 2) (first row, second column).
Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The next 2t lines contain descriptions of the test cases.
In the description of each test case, the first line contains two integers n and m (1 ≤ n, m ≤ 10^6) — the height and width of the field that the robot is located on. The second line of the description is a string s consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from 1 to 10^6 commands.
It is guaranteed that the total length of s over all test cases does not exceed 10^6.
Output
Print t lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers r (1 ≤ r ≤ n) and c (1 ≤ c ≤ m), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible.
If there are several such cells, you may output any of them.
Example
Input
4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU
Output
1 1
1 2
2 1
3 2 | import sys
input = sys.stdin.readline
def solution():
n,m = [int(x) for x in input().strip().split()]
s = input().strip()
minx = 1
maxx = n
miny = 1
maxy = m
res = ['1','1']
updown = 0
leftright = 0
for command in s:
if (command == 'U'): updown -=1
if (command == 'D'): updown +=1
if (command == 'L'): leftright-=1
if (command == 'R'): leftright+=1
minx = max(minx, 1-updown)
maxx = min(maxx, n-updown)
miny = max(miny, 1-leftright)
maxy = min(maxy, m-leftright)
if (minx > maxx or miny > maxy): break
res = [str(minx),str(miny)]
print(' '.join(res))
for _ in range(int(input().strip())):
solution()
|
The robot is located on a checkered rectangular board of size n × m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right.
The robot is able to move from the current cell to one of the four cells adjacent by side.
Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively.
The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move.
* If the robot moves beyond the edge of the board, it falls and breaks.
* If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore).
Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.
Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).
Input
The first line contains an integer t (1 ≤ t ≤ 10000) — the number of test cases in the test.
Each test case's description is preceded by a blank line. Next is a line that contains integers n and m (1 ≤ n ≤ 2000; 1 ≤ m ≤ 2000) — the height and width of the board. This line followed by n lines, the i-th of which describes the i-th line of the board. Each of them is exactly m letters long and consists of symbols 'L', 'R', 'D' and 'U'.
It is guaranteed that the sum of sizes of all boards in the input does not exceed 4⋅10^6.
Output
For each test case, output three integers r, c and d (1 ≤ r ≤ n; 1 ≤ c ≤ m; d ≥ 0), which denote that the robot should start moving from cell (r, c) to make the maximum number of moves d. If there are several answers, output any of them.
Example
Input
7
1 1
R
1 3
RRL
2 2
DL
RU
2 2
UD
RU
3 2
DL
UL
RU
4 4
RRRD
RUUD
URUD
ULLR
4 4
DDLU
RDDU
UUUU
RDLD
Output
1 1 1
1 1 3
1 1 4
2 1 3
3 1 5
4 3 12
1 1 4 | #include <bits/stdc++.h>
const int N = 2010;
int n, m;
char mp[N][N];
int a, b, d;
int f[N][N];
bool vis[N][N];
bool flg;
int top;
std::pair<int, int> stk[N * N];
int dx[N], dy[N];
int dfs(int x, int y) {
stk[++top] = std::make_pair(x, y);
if (x == 0 || y == 0 || x > n || y > m) return 0;
if (vis[x][y]) {
flg = true;
return 0;
}
vis[x][y] = true;
if (f[x][y]) return f[x][y];
return f[x][y] = dfs(x + dx[mp[x][y]], y + dy[mp[x][y]]) + 1;
}
void solv() {
a = 1, b = 1, d = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%s", mp[i] + 1);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) f[i][j] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
flg = false;
if (f[i][j] == 0) {
top = 0;
dfs(i, j);
}
if (flg) {
std::pair<int, int> tmp = stk[top], tmp2 = stk[top];
int val = f[tmp.first][tmp.second];
do {
vis[tmp2.first][tmp2.second] = false;
f[tmp2.first][tmp2.second] = val;
--top;
tmp2 = stk[top];
} while (stk[top] != tmp);
}
std::pair<int, int> tmp2;
while (top) {
tmp2 = stk[top];
vis[tmp2.first][tmp2.second] = false;
--top;
}
if (f[i][j] > d) {
d = f[i][j];
a = i;
b = j;
}
}
printf("%d %d %d\n", a, b, d);
}
int main() {
dx['U'] = -1;
dx['D'] = 1;
dy['L'] = -1;
dy['R'] = 1;
int cza;
scanf("%d", &cza);
while (cza--) solv();
return 0;
}
|
A known chef has prepared n dishes: the i-th dish consists of a_i grams of fish and b_i grams of meat.
The banquet organizers estimate the balance of n dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat.
Technically, the balance equals to \left|∑_{i=1}^n a_i - ∑_{i=1}^n b_i\right|. The smaller the balance, the better.
In order to improve the balance, a taster was invited. He will eat exactly m grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he should eat exactly m grams of each dish in total.
Determine how much of what type of food the taster should eat from each dish so that the value of the balance is as minimal as possible. If there are several correct answers, you may choose any of them.
Input
The first line of input data contains an integer t (1 ≤ t ≤ 10^4) — the number of the test cases.
Each test case's description is preceded by a blank line. Next comes a line that contains integers n and m (1 ≤ n ≤ 2 ⋅ 10^5; 0 ≤ m ≤ 10^6). The next n lines describe dishes, the i-th of them contains a pair of integers a_i and b_i (0 ≤ a_i, b_i ≤ 10^6) — the masses of fish and meat in the i-th dish.
It is guaranteed that it is possible to eat m grams of food from each dish. In other words, m ≤ a_i+b_i for all i from 1 to n inclusive.
The sum of all n values over all test cases in the test does not exceed 2 ⋅ 10^5.
Output
For each test case, print on the first line the minimal balance value that can be achieved by eating exactly m grams of food from each dish.
Then print n lines that describe a way to do this: the i-th line should contain two integers x_i and y_i (0 ≤ x_i ≤ a_i; 0 ≤ y_i ≤ b_i; x_i+y_i=m), where x_i is how many grams of fish taster should eat from the i-th meal and y_i is how many grams of meat.
If there are several ways to achieve a minimal balance, find any of them.
Example
Input
8
1 5
3 4
1 6
3 4
2 2
1 3
4 2
2 4
1 3
1 7
3 6
1 7
1 8
1 9
3 6
1 8
1 9
30 10
3 4
3 1
3 2
4 1
5 4
0 7
6 4
0 8
4 1
5 3
Output
0
2 3
1
3 3
0
1 1
1 1
2
1 3
0 4
3
0 6
0 6
0 6
7
1 5
1 5
6 0
0
3 1
3 1
3 1
0
0 4
2 2
0 4
3 1
1 3 | #include <bits/stdc++.h>
#pragma GCC optimize(3)
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
using namespace std;
const long long N = 2e5 + 10;
long long lim[N], a[N], b[N];
void solve() {}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long t;
cin >> t;
while (t--) {
long long n, m, i;
long long dl = 0, dr = 0;
cin >> n >> m;
for (i = 1; i <= n; i++) {
long long x, y, l, r;
cin >> x >> y;
a[i] = min(x, m);
b[i] = m - a[i];
if (x <= m)
l = m - x - y;
else
l = x - m - y;
if (y <= m)
r = x - m + y;
else
r = x + m - y;
assert(l <= r);
lim[i] = r - l >> 1;
dl -= l;
dr += r - l;
}
if (dl >= 0 && dl <= dr) {
cout << (dl & 1) << '\n';
dl >>= 1;
for (i = 1; i <= n; i++)
if (dl >= lim[i])
dl -= lim[i], cout << a[i] - lim[i] << ' ' << b[i] + lim[i] << '\n';
else
cout << a[i] - dl << ' ' << b[i] + dl << '\n', dl = 0;
} else if (dl < 0) {
cout << -dl << endl;
for (i = 1; i <= n; i++) cout << a[i] << ' ' << b[i] << endl;
} else {
cout << dl - dr << endl;
for (i = 1; i <= n; i++)
cout << a[i] - lim[i] << ' ' << b[i] + lim[i] << '\n';
}
}
}
|
The chef has cooked n dishes yet again: the i-th dish consists of a_i grams of fish and b_i grams of meat.
Banquet organizers consider two dishes i and j equal if a_i=a_j and b_i=b_j at the same time.
The banquet organizers estimate the variety of n dishes as follows. The variety of a set of dishes is equal to the number of different dishes in it. The less variety is, the better.
In order to reduce the variety, a taster was invited. He will eat exactly m_i grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he will eat exactly m_i grams of the i-th dish in total.
Determine how much of what type of food the taster should eat from each dish so that the value of variety is the minimum possible. If there are several correct answers, you may output any of them.
Input
The first line of input data contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Each test case's description is preceded by a blank line. Next comes a line that contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of dishes. Then follows n lines, i-th of which contains three integers a_i, b_i and m_i (0 ≤ a_i, b_i ≤ 10^6; 0 ≤ m_i ≤ a_i+b_i) — the mass of fish in i-th dish, the mass of meat in i-th dish and how many grams in total the taster should eat in i-th dish.
The sum of all n values for all input data sets in the test does not exceed 2 ⋅ 10^5.
Output
For each test case, print on the first line the minimum value of variety that can be achieved by eating exactly m_i grams of food (for all i from 1 to n) from a dish i.
Then print n lines that describe a way to do this: the i-th line should contain two integers x_i and y_i (0 ≤ x_i ≤ a_i; 0 ≤ y_i ≤ b_i; x_i+y_i=m_i), where x_i is how many grams of fish the taster should eat from i-th dish, and y_i is how many grams of meat.
If there are several ways to achieve a minimum balance, print any of them.
Example
Input
5
3
10 10 2
9 9 0
10 9 1
2
3 4 1
5 1 2
3
7 2 5
6 5 4
5 5 6
1
13 42 50
5
5 7 12
3 1 4
7 3 7
0 0 0
4 1 5
Output
1
1 1
0 0
1 0
2
0 1
1 1
2
3 2
0 4
1 5
1
8 42
2
5 7
3 1
4 3
0 0
4 1 | import io,os
import heapq
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = 2147483647
def main(t):
space = input()
n = int(input())
dic = {}
target = [-1]*n
temp = []
for i in range(n):
a,b,req = map(int,input().split())
temp.append([a,b,req])
if a+b-req not in dic: dic[a+b-req] = []
maxa = min(a+b-req,a)
mina = max(a-req,0)
dic[a+b-req].append([mina,maxa,i])
ans = 0
for key in dic:
dic[key] = sorted(dic[key])
dic[key].append([inf,inf,-1])
heap = []
indexlist = []
minimum = -1
for [front,rear,index] in dic[key]:
if front > minimum:
if indexlist: ans += 1
while indexlist:
target[indexlist.pop()] = minimum
minimum = rear
indexlist = [index]
else:
indexlist.append(index)
minimum = min(minimum,rear)
# print(target)
print(ans)
for i,ele in enumerate(temp):
rest = ele[0]+ele[1]-ele[2]
print(ele[0]-target[i], ele[2]+target[i]-ele[0] )
# print(dic)
# print(targeta)
T = int(input())
t = 1
while t<=T:
main(t)
t += 1
|
Given n, find any array a_1, a_2, …, a_n of integers such that all of the following conditions hold:
* 1 ≤ a_i ≤ 10^9 for every i from 1 to n.
* a_1 < a_2 < … <a_n
* For every i from 2 to n, a_i isn't divisible by a_{i-1}
It can be shown that such an array always exists under the constraints of the problem.
Input
The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows.
The only line of each test case contains a single integer n (1 ≤ n ≤ 1000).
It is guaranteed that the sum of n over all test cases does not exceed 10^4.
Output
For each test case print n integers a_1, a_2, …, a_n — the array you found. If there are multiple arrays satisfying all the conditions, print any of them.
Example
Input
3
1
2
7
Output
1
2 3
111 1111 11111 111111 1111111 11111111 111111111
Note
In the first test case, array [1] satisfies all the conditions.
In the second test case, array [2, 3] satisfies all the conditions, as 2<3 and 3 is not divisible by 2.
In the third test case, array [111, 1111, 11111, 111111, 1111111, 11111111, 111111111] satisfies all the conditions, as it's increasing and a_i isn't divisible by a_{i-1} for any i from 2 to 7. | for i in range(int(input())):print(*range(2, int(input()) + 2)) |
You are given three integers n, a, b. Determine if there exists a permutation p_1, p_2, …, p_n of integers from 1 to n, such that:
* There are exactly a integers i with 2 ≤ i ≤ n-1 such that p_{i-1} < p_i > p_{i+1} (in other words, there are exactly a local maximums).
* There are exactly b integers i with 2 ≤ i ≤ n-1 such that p_{i-1} > p_i < p_{i+1} (in other words, there are exactly b local minimums).
If such permutations exist, find any such permutation.
Input
The first line of the input contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The description of test cases follows.
The only line of each test case contains three integers n, a and b (2 ≤ n ≤ 10^5, 0 ≤ a,b ≤ n).
The sum of n over all test cases doesn't exceed 10^5.
Output
For each test case, if there is no permutation with the requested properties, output -1.
Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.
Example
Input
3
4 1 1
6 1 2
6 4 0
Output
1 3 2 4
4 2 3 1 5 6
-1
Note
In the first test case, one example of such permutations is [1, 3, 2, 4]. In it p_1 < p_2 > p_3, and 2 is the only such index, and p_2> p_3 < p_4, and 3 the only such index.
One can show that there is no such permutation for the third test case. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pw;
static String nextToken() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(nextToken());
}
static long nextLong() {
return Long.parseLong(nextToken());
}
static double nextDouble() {
return Double.parseDouble(nextToken());
}
static String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new IllegalArgumentException();
}
}
static char nextChar() {
try {
return (char) br.read();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int t = 1;
t = nextInt();
while (t-- > 0) {
solve();
}
pw.close();
}
private static void solve() {
int n = nextInt();
int a = nextInt();
int b = nextInt();
if (!check(n, a, b)) {
pw.println(-1);
} else {
int l = 1;
int r = n;
int k;
if (a>b) {
k = a;
for (int i = 0; i < k; i++) {
pw.print(l++ + " ");
pw.print(r-- + " ");
}
for (int i = r; i >= l; i--) {
pw.print(i + " ");
}
pw.println();
} else if (b > a) {
k=b;
for (int i = 0; i < k; i++) {
pw.print(r-- + " ");
pw.print(l++ + " ");
}
for (int i = l; i <=r; i++) {
pw.print(i + " ");
}
pw.println();
} else {
k=a;
for (int i = 0; i < k; i++) {
pw.print(r-- + " ");
pw.print(l++ + " ");
}
for (int i = r; i >= l; i--) {
pw.print(i + " ");
}
pw.println();
}
}
}
private static boolean check(int n, int a, int b) {
if (a-b>1) return false;
if (b-a>1) return false;
if (b+a > n-2) return false;
return true;
}
} |
n players are playing a game.
There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map.
You are the game master and want to organize a tournament. There will be a total of n-1 battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament.
In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^5) — the number of players.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9, a_i ≠ a_j for i ≠ j), where a_i is the strength of the i-th player on the first map.
The third line of each test case contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9, b_i ≠ b_j for i ≠ j), where b_i is the strength of the i-th player on the second map.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case print a string of length n. i-th character should be "1" if the i-th player can win the tournament, or "0" otherwise.
Example
Input
3
4
1 2 3 4
1 2 3 4
4
11 12 20 21
44 22 11 30
1
1000000000
1000000000
Output
0001
1111
1
Note
In the first test case, the 4-th player will beat any other player on any game, so he will definitely win the tournament.
In the second test case, everyone can be a winner.
In the third test case, there is only one player. Clearly, he will win the tournament. | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
int n;
while (t--) {
cin >> n;
vector<pair<pair<long long int, long long int>, int> > Data(n);
for (int i = 0; i < n; i++) cin >> Data[i].first.first;
for (int i = 0; i < n; i++) cin >> Data[i].first.second;
for (int i = 0; i < n; i++) Data[i].second = i;
sort(Data.begin(), Data.end());
vector<bool> sol(n, 0);
sol[Data[n - 1].second] = 1;
long long int min_ganar_segundo = Data[n - 1].first.second;
int j = n - 1;
for (int i = n - 1; i >= 0; i--) {
if (Data[i].first.second > min_ganar_segundo) {
for (int k = i; k < j; k++) {
sol[Data[k].second] = 1;
min_ganar_segundo = min(min_ganar_segundo, Data[k].first.second);
}
j = i;
}
}
for (int i = 0; i < n; i++) cout << sol[i];
cout << endl;
}
}
|
You are given n dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.
The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each 1 ≤ i ≤ n the color of the right cell of the i-th domino is different from the color of the left cell of the ((i mod n)+1)-st domino.
Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.
Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).
As this number can be very big, output it modulo 998 244 353.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 10^5) — the number of dominoes.
The next n lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
Output
Print a single integer — the answer to the problem.
Examples
Input
1
?W
Output
1
Input
2
??
W?
Output
2
Input
4
BB
??
W?
??
Output
10
Note
In the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.
In the second test case, there are only 2 such colorings:
BB WW and WB WB. | #include <bits/stdc++.h>
using namespace std;
char ch[100010][5];
const int mod = 998244353;
int fac[200010], facinv[200010];
long long qpow(long long a, long long b) {
long long m = 1;
while (b) {
if (b & 1) m = m * a % mod;
b >>= 1;
a = a * a % mod;
}
return m;
}
void init(int x) {
fac[0] = 1;
int i;
for (i = 1; i <= x; ++i) fac[i] = (long long)fac[i - 1] * i % mod;
facinv[x] = qpow(fac[x], mod - 2);
for (i = x; i >= 1; --i) facinv[i - 1] = (long long)facinv[i] * i % mod;
}
long long C(int a, int b) {
if (b < 0 || b > a) return 0;
return (long long)fac[a] * facinv[b] % mod * facinv[a - b] % mod;
}
int main() {
init(200000);
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
int i, x = 0, x1 = 0;
for (i = 1; i <= n; ++i) {
cin >> ch[i];
if (ch[i][0] == 'W') {
if (ch[i][1] == 'W')
++x;
else if (ch[i][1] == '?')
++x1;
} else if (ch[i][0] == 'B') {
if (ch[i][1] == 'B')
--x;
else if (ch[i][1] == '?')
--x, ++x1;
} else {
if (ch[i][1] == 'W')
++x1;
else if (ch[i][1] == 'B')
++x1, --x;
else
x1 += 2, --x;
}
}
long long ans = C(x1, -x);
bool flag = 0;
for (i = 1; i <= n; ++i) {
if (ch[i][0] == ch[i][1]) {
if (ch[i][0] != '?') flag = 1;
}
}
if (!flag) {
int cnt1 = 0, cnt2 = 0, cnt = 0;
for (i = 1; i <= n; ++i) {
if (ch[i][0] == 'W')
++cnt1;
else if (ch[i][0] == 'B')
++cnt2;
else {
if (ch[i][1] == 'W')
++cnt2;
else if (ch[i][1] == 'B')
++cnt1;
else
++cnt;
}
}
if (!cnt1 || !cnt2) {
if (!cnt1 && !cnt2)
ans = (ans + mod - qpow(2, cnt) + 2) % mod;
else
ans = (ans + mod - qpow(2, cnt) + 1) % mod;
} else
ans = (ans + mod - qpow(2, cnt)) % mod;
}
cout << ans << '\n';
return 0;
}
|
On an endless checkered sheet of paper, n cells are chosen and colored in three colors, where n is divisible by 3. It turns out that there are exactly n/3 marked cells of each of three colors!
Find the largest such k that it's possible to choose k/3 cells of each color, remove all other marked cells, and then select three rectangles with sides parallel to the grid lines so that the following conditions hold:
* No two rectangles can intersect (but they can share a part of the boundary). In other words, the area of intersection of any two of these rectangles must be 0.
* The i-th rectangle contains all the chosen cells of the i-th color and no chosen cells of other colors, for i = 1, 2, 3.
Input
The first line of the input contains a single integer n — the number of the marked cells (3 ≤ n ≤ 10^5, n is divisible by 3).
The i-th of the following n lines contains three integers x_i, y_i, c_i (|x_i|,|y_i| ≤ 10^9; 1 ≤ c_i ≤ 3), where (x_i, y_i) are the coordinates of the i-th marked cell and c_i is its color.
It's guaranteed that all cells (x_i, y_i) in the input are distinct, and that there are exactly n/3 cells of each color.
Output
Output a single integer k — the largest number of cells you can leave.
Examples
Input
9
2 3 1
4 1 2
2 1 3
3 4 1
5 3 2
4 4 3
2 4 1
5 2 2
3 5 3
Output
6
Input
3
1 1 1
2 2 2
3 3 3
Output
3
Note
In the first sample, it's possible to leave 6 cells with indexes 1, 5, 6, 7, 8, 9.
In the second sample, it's possible to leave 3 cells with indexes 1, 2, 3. | #include <bits/stdc++.h>
using namespace std;
int gi() {
int x = 0, c = getchar();
bool f = 0;
for (; !isdigit(c); c = getchar())
if (c == '-') f = 1;
for (; isdigit(c); c = getchar()) x = x * 10 + (c & 15);
return f ? -x : x;
}
constexpr int N = (int)1e5 + 5;
int n, x[N], y[N], c[N], _n, _m;
vector<int> _x, _y, hang[3][N], lie[3][N];
bool _check1(int k, int a, int b, int c) {
int cnt = 0;
for (int i = 1; i <= _n - 2; ++i) {
cnt += hang[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = i + 1; j < _n; ++j) {
cnt += hang[b][j].size();
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _n; ++l) {
cnt += hang[c][l].size();
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check2(int k, int a, int b, int c) {
int cnt = 0;
for (int i = 1; i <= _m - 2; ++i) {
cnt += lie[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = i + 1; j < _m; ++j) {
cnt += lie[b][j].size();
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _m; ++l) {
cnt += lie[c][l].size();
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check3(int k, int a, int b, int c) {
int cnt = 0;
for (int i = 1; i < _n; ++i) {
cnt += hang[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = 1; j < _m; ++j) {
for (int x : lie[b][j]) {
if (x >= i + 1) cnt++;
}
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _m; ++l) {
for (int x : lie[c][l]) {
if (x >= i + 1) cnt++;
}
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check4(int k, int a, int b, int c) {
int cnt = 0;
for (int i = 1; i < _m; ++i) {
cnt += lie[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = 1; j < _n; ++j) {
for (int x : hang[b][j]) {
if (x >= i + 1) cnt++;
}
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _n; ++l) {
for (int x : hang[c][l]) {
if (x >= i + 1) cnt++;
}
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check5(int k, int a, int b, int c) {
int cnt = 0;
for (int i = _n; i > 1; --i) {
cnt += hang[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = 1; j < _m; ++j) {
for (int x : lie[b][j]) {
if (x <= i - 1) cnt++;
}
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _m; ++l) {
for (int x : lie[c][l]) {
if (x <= i - 1) cnt++;
}
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check6(int k, int a, int b, int c) {
int cnt = 0;
for (int i = _m; i > 1; --i) {
cnt += lie[a][i].size();
if (cnt >= k) {
cnt = 0;
for (int j = 1; j < _n; ++j) {
for (int x : hang[b][j]) {
if (x <= i - 1) cnt++;
}
if (cnt >= k) {
cnt = 0;
for (int l = j + 1; l <= _n; ++l) {
for (int x : hang[c][l]) {
if (x <= i - 1) cnt++;
}
}
return cnt >= k;
}
}
return 0;
}
}
return 0;
}
bool _check(int k, int a, int b, int c) {
return _check1(k, a, b, c) || _check2(k, a, b, c) || _check3(k, a, b, c) ||
_check4(k, a, b, c) || _check5(k, a, b, c) || _check6(k, a, b, c);
}
bool check(int k) {
return _check(k, 0, 1, 2) || _check(k, 0, 2, 1) || _check(k, 1, 0, 2) ||
_check(k, 1, 2, 0) || _check(k, 2, 0, 1) || _check(k, 2, 1, 0);
}
int main() {
n = gi();
for (int i = 1; i <= n; ++i) {
x[i] = gi(), y[i] = gi(), c[i] = gi();
_x.push_back(x[i]);
_y.push_back(y[i]);
}
sort(_x.begin(), _x.end());
sort(_y.begin(), _y.end());
_x.resize(unique(_x.begin(), _x.end()) - _x.begin());
_y.resize(unique(_y.begin(), _y.end()) - _y.begin());
_n = _x.size(), _m = _y.size();
for (int i = 1; i <= n; ++i) {
x[i] = lower_bound(_x.begin(), _x.end(), x[i]) - _x.begin() + 1;
y[i] = lower_bound(_y.begin(), _y.end(), y[i]) - _y.begin() + 1;
hang[c[i] - 1][x[i]].push_back(y[i]);
lie[c[i] - 1][y[i]].push_back(x[i]);
}
int l = 2, r = n / 3;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid))
l = mid + 1;
else
r = mid - 1;
}
printf("%d\n", 3 * r);
return 0;
}
|
For an array c of nonnegative integers, MEX(c) denotes the smallest nonnegative integer that doesn't appear in it. For example, MEX([0, 1, 3]) = 2, MEX([42]) = 0.
You are given integers n, k, and an array [b_1, b_2, …, b_n].
Find the number of arrays [a_1, a_2, …, a_n], for which the following conditions hold:
* 0 ≤ a_i ≤ n for each i for each i from 1 to n.
* |MEX([a_1, a_2, …, a_i]) - b_i| ≤ k for each i from 1 to n.
As this number can be very big, output it modulo 998 244 353.
Input
The first line of the input contains two integers n, k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 50).
The second line of the input contains n integers b_1, b_2, …, b_n (-k ≤ b_i ≤ n+k) — elements of the array b.
Output
Output a single integer — the number of arrays which satisfy the conditions from the statement, modulo 998 244 353.
Examples
Input
4 0
0 0 0 0
Output
256
Input
4 1
0 0 0 0
Output
431
Input
4 1
0 0 1 1
Output
509
Input
5 2
0 0 2 2 0
Output
6546
Input
3 2
-2 0 4
Output
11 | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
return f == -1 ? ~x + 1 : x;
}
int n, k;
int b[2010];
int dp[2][110][2010];
int D[5310];
int fac[4010], ifac[4010];
const int mod = 998244353;
inline int qpow(int x, int k = mod - 2) {
int res = 1;
while (k) {
if (k & 1) res = 1ll * res * x % mod;
x = 1ll * x * x % mod;
k >>= 1;
}
return res;
}
int main() {
n = read(), k = read();
for (int i = 1; i <= n; ++i) b[i] = read();
dp[0][k][0] = 1;
bool fl = 0;
fac[0] = 1;
for (int i = 1; i <= n; ++i) fac[i] = 1ll * fac[i - 1] * i % mod;
ifac[n] = qpow(fac[n]);
for (int i = n - 1; i >= 0; --i) ifac[i] = 1ll * ifac[i + 1] * (i + 1) % mod;
for (int i = 1; i <= n; ++i) {
fl ^= 1;
memset(dp[fl], 0, sizeof(dp[fl]));
memset(D, 0, sizeof(D));
int it = -min(k, b[i - 1]);
for (int j = -min(b[i], k); j <= k; ++j) {
int val = b[i] + j;
while (it < val - b[i - 1] && it <= k) {
for (int l = 0; l <= i; ++l)
(D[l + b[i - 1] + it] +=
1ll * dp[fl ^ 1][it + k][l] * fac[l] % mod) %= mod;
++it;
}
for (int l = 0; l <= i; ++l) {
if (l + val > 0)
dp[fl][j + k][l] = 1ll * D[l + val - 1] * ifac[l] % mod;
if (abs(val - b[i - 1]) <= k) {
(dp[fl][j + k][l] +=
1ll * (val + l) * dp[fl ^ 1][k + val - b[i - 1]][l] % mod) %= mod;
if (l)
(dp[fl][j + k][l] += dp[fl ^ 1][k + val - b[i - 1]][l - 1]) %= mod;
}
}
}
}
int ans = 0;
for (int i = -min(b[n], k); i <= k && i + b[n] <= n; ++i) {
for (int l = 0; l <= n && b[n] + i + l <= n; ++l) {
(ans += 1ll * dp[fl][i + k][l] * fac[n - (b[n] + i)] % mod *
ifac[n - (b[n] + i + l)] % mod) %= mod;
}
}
printf("%d\n", ans);
}
|
You are given m strings and a tree on n nodes. Each edge has some letter written on it.
You have to answer q queries. Each query is described by 4 integers u, v, l and r. The answer to the query is the total number of occurrences of str(u,v) in strings with indices from l to r. str(u,v) is defined as the string that is made by concatenating letters written on the edges on the shortest path from u to v (in order that they are traversed).
Input
The first line of the input contains three integers n, m and q (2 ≤ n ≤ 10^5, 1 ≤ m,q ≤ 10^5).
The i-th of the following n-1 lines contains two integers u_i, v_i and a lowercase Latin letter c_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting the edge between nodes u_i, v_i with a character c_i on it.
It's guaranteed that these edges form a tree.
The following m lines contain the strings consisting of lowercase Latin letters. The total length of those strings does not exceed 10^5.
Then q lines follow, each containing four integers u, v, l and r (1 ≤ u,v ≤ n, u ≠ v, 1 ≤ l ≤ r ≤ m), denoting the queries.
Output
For each query print a single integer — the answer to the query.
Examples
Input
2 5 3
1 2 a
aab
abab
aaa
b
a
2 1 1 5
1 2 1 3
2 1 3 5
Output
8
7
4
Input
9 5 6
1 2 a
2 7 c
1 3 b
3 4 b
4 6 b
3 5 a
5 8 b
5 9 c
ababa
cabbb
bac
bbbac
abacaba
2 7 1 4
2 5 1 5
6 3 4 4
6 9 4 5
5 7 3 5
5 3 1 5
Output
3
4
2
1
1
10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 6e5 + 10;
int n, m, q, k, head[N], tot, st[M], ed[M], ans[N];
char s[M];
struct node {
int to, nxt;
char c;
} e[N << 1];
void add(int x, int y, char c) {
e[++k].to = y;
e[k].nxt = head[x];
head[x] = k;
e[k].c = c;
}
namespace SA {
int sa[M], rnk[M], x[M], y[M], height[M], c[M], minn[M][20], getlog[M];
void work() {
int m = 255;
for (int i = 1; i <= tot; i++) c[x[i] = s[i]]++;
for (int i = 1; i <= m; i++) c[i] += c[i - 1];
for (int i = tot; i; i--) sa[c[x[i]]--] = i;
for (int k = 1; k <= tot; k <<= 1) {
int now = 0;
for (int i = tot - k + 1; i <= tot; i++) y[++now] = i;
for (int i = 1; i <= tot; i++)
if (sa[i] > k) y[++now] = sa[i] - k;
for (int i = 1; i <= m; i++) c[i] = 0;
for (int i = 1; i <= tot; i++) c[x[y[i]]]++;
for (int i = 1; i <= m; i++) c[i] += c[i - 1];
for (int i = tot; i; i--) sa[c[x[y[i]]]--] = y[i];
swap(x, y);
now = 1;
x[sa[1]] = 1;
for (int i = 2; i <= tot; i++)
x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k])
? now
: ++now;
if (now == tot) break;
m = now;
}
for (int i = 1; i <= tot; i++) rnk[sa[i]] = i;
int k = 0;
for (int i = 1; i <= tot; i++) {
if (rnk[i] == 1) continue;
int j = sa[rnk[i] - 1];
if (k) k--;
while (i + k <= tot && j + k <= tot && s[i + k] == s[j + k]) k++;
height[rnk[i]] = k;
}
for (int i = 2; i <= tot; i++) minn[i][0] = height[i];
for (int j = 1; j <= 19; j++)
for (int i = 2; i + (1 << j) - 1 <= tot; i++)
minn[i][j] = min(minn[i][j - 1], minn[i + (1 << j - 1)][j - 1]);
for (int i = 2; i <= tot; i++) getlog[i] = getlog[i >> 1] + 1;
}
int query(int x, int y) {
if (x == y) return tot - x + 1;
x = rnk[x];
y = rnk[y];
if (x > y) swap(x, y);
x++;
int k = getlog[y - x + 1];
return min(minn[x][k], minn[y - (1 << k) + 1][k]);
}
} // namespace SA
namespace TREE {
int sz[N], son[N], fa[N], dep[N];
char val[N];
void dfs1(int u, int lst, char c) {
sz[u] = 1;
dep[u] = dep[lst] + 1;
fa[u] = lst;
val[u] = c;
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
if (v == lst) continue;
dfs1(v, u, e[i].c);
sz[u] += sz[v];
if (sz[son[u]] < sz[v]) son[u] = v;
}
}
int top[N], dfn[N], ord[N], cnt, pnt1[N], pnt2[N];
void dfs2(int u, int lst, int tp) {
dfn[u] = ++cnt;
ord[cnt] = u;
top[u] = tp;
if (son[u]) dfs2(son[u], u, tp);
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
if (v == lst || v == son[u]) continue;
dfs2(v, u, v);
}
}
void merge() {
for (int i = 1; i <= n; i++) s[++tot] = val[ord[i]], pnt1[ord[i]] = tot;
s[++tot] = '#';
for (int i = n; i; i--) s[++tot] = val[ord[i]], pnt2[ord[i]] = tot;
}
int lca(int x, int y) {
while (top[x] != top[y]) {
if (dep[top[x]] < dep[top[y]]) swap(x, y);
x = fa[top[x]];
}
if (dep[x] < dep[y]) swap(x, y);
return y;
}
vector<pair<int, int> > vec1, vec2, vec;
int comp(int mid) {
int pos = SA::sa[mid];
for (auto it : vec) {
int lcp = SA::query(it.first, pos), len = it.second - it.first + 1;
if (lcp >= len)
pos += len;
else {
if (s[pos + lcp] < s[it.first + lcp]) return 0;
return 1;
}
}
return 2;
}
pair<int, int> work(int x, int y) {
int z = lca(x, y);
vec1.clear();
vec2.clear();
vec.clear();
while (top[x] != top[z]) {
vec1.push_back(make_pair(pnt2[x], pnt2[top[x]]));
x = fa[top[x]];
}
if (x != z) vec1.push_back(make_pair(pnt2[x], pnt2[son[z]]));
while (top[y] != top[z]) {
vec2.push_back(make_pair(pnt1[top[y]], pnt1[y]));
y = fa[top[y]];
}
if (y != z) vec2.push_back(make_pair(pnt1[son[z]], pnt1[y]));
reverse(vec2.begin(), vec2.end());
for (auto it : vec1) vec.push_back(it);
for (auto it : vec2) vec.push_back(it);
int l = 1, r = tot, mid, resl = tot + 1;
while (l <= r) {
mid = l + r >> 1;
int tmp = comp(mid);
if (tmp == 2)
resl = min(resl, mid), r = mid - 1;
else if (tmp == 1)
r = mid - 1;
else
l = mid + 1;
}
l = 1;
r = tot;
int resr = 0;
while (l <= r) {
mid = l + r >> 1;
int tmp = comp(mid);
if (tmp == 2)
resr = max(resr, mid), l = mid + 1;
else if (tmp == 1)
r = mid - 1;
else
l = mid + 1;
}
return make_pair(resl, resr);
}
} // namespace TREE
struct data {
int ql, qr, ord, opt;
data(int ql = 0, int qr = 0, int ord = 0, int opt = 0)
: ql(ql), qr(qr), ord(ord), opt(opt) {}
};
vector<data> qry[M];
namespace BIT {
int tr[M];
void update(int x) {
for (; x <= tot; x += x & (-x)) tr[x]++;
}
int query(int x) {
int res = 0;
for (; x; x -= x & (-x)) res += tr[x];
return res;
}
void work() {
for (int i = 1; i <= tot; i++) {
update(SA::sa[i]);
for (auto it : qry[i])
ans[it.ord] += it.opt * (query(it.qr) - query(it.ql - 1));
}
}
} // namespace BIT
int main() {
scanf("%d%d%d", &n, &m, &q);
char tmp[M];
for (int i = 1, x, y; i < n; i++)
scanf("%d%d%s", &x, &y, tmp + 1), add(x, y, tmp[1]), add(y, x, tmp[1]);
for (int i = 1; i <= m; i++) {
scanf("%s", tmp + 1);
int len = strlen(tmp + 1);
st[i] = tot + 1;
for (int j = 1; j <= len; j++) s[++tot] = tmp[j];
ed[i] = tot;
s[++tot] = '#';
}
TREE::dfs1(1, 1, '$');
TREE::dfs2(1, 1, 1);
TREE::merge();
SA::work();
for (int i = 1; i <= q; i++) {
int u, v, l, r;
scanf("%d%d%d%d", &u, &v, &l, &r);
pair<int, int> rge = TREE::work(u, v);
if (rge.first > rge.second)
ans[i] = 0;
else {
qry[rge.first - 1].push_back(data(st[l], ed[r], i, -1));
qry[rge.second].push_back(data(st[l], ed[r], i, 1));
}
}
BIT::work();
for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
}
|
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer x with p zeros appended to its end.
Now Monocarp asks you to compare these two numbers. Can you help him?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.
The first line of each testcase contains two integers x_1 and p_1 (1 ≤ x_1 ≤ 10^6; 0 ≤ p_1 ≤ 10^6) — the description of the first number.
The second line of each testcase contains two integers x_2 and p_2 (1 ≤ x_2 ≤ 10^6; 0 ≤ p_2 ≤ 10^6) — the description of the second number.
Output
For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.
Example
Input
5
2 1
19 0
10 2
100 1
1999 0
2 3
1 0
1 0
99 0
1 2
Output
>
=
<
=
<
Note
The comparisons in the example are: 20 > 19, 1000 = 1000, 1999 < 2000, 1 = 1, 99 < 100. | import java.io.*;
import java.util.*;
public class Aqueous {
static MyScanner sc = new MyScanner();
public static void main(String[] args){
int t = sc.nextInt();
while(t-->0) {
String x1 = sc.next();
int n1 = sc.nextInt();
String x2 =sc.next();
int n2 = sc.nextInt();
if(x1.length()==x2.length()) {
if(n1<n2) {
System.out.println("<");
}
else if(n1>n2) {
System.out.println(">");
}
else {
int one = Integer.parseInt(x1);
int two = Integer.parseInt(x2);
if(one>two) {
System.out.println(">");
}
else if(one<two) {
System.out.println("<");
}
else {
System.out.println("=");
}
}
}
else if(x1.length()<x2.length()) {
StringBuffer sb = new StringBuffer();
sb.append(x1);
while(n1>0 && sb.length()<x2.length()) {
n1--;
sb.append('0');
}
if(n1==0) {
if(sb.length()==x2.length()) {
if(n2>0) {
System.out.println("<");
}
else {
int one = Integer.parseInt(sb.toString());
int two = Integer.parseInt(x2);
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else {
System.out.println("<");
}
}
}
else {
if(n1>n2) {
System.out.println(">");
}
else if(n1==n2) {
int one = Integer.parseInt(sb.toString());
int two = Integer.parseInt(x2);
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else{
System.out.println("<");
}
}
else {
System.out.println("<");
}
}
}
else {
if(n1>n2) {
System.out.println(">");
}
else if(n1==n2) {
int one = Integer.parseInt(sb.toString());
int two = Integer.parseInt(x2);
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else{
System.out.println("<");
}
}
else {
System.out.println("<");
}
}
}
else {
StringBuffer sb = new StringBuffer();
sb.append(x2);
while(n2>0 && sb.length()<x1.length()) {
n2--;
sb.append('0');
}
if(n2==0) {
if(x1.length()==sb.length()) {
if(n1>0) {
System.out.println(">");
}
else {
int one = Integer.parseInt(x1);
int two = Integer.parseInt(sb.toString());
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else{
System.out.println("<");
}
}
}
else {
if(n1>0) {
System.out.println(">");
}
else {
int one = Integer.parseInt(x1);
int two = Integer.parseInt(sb.toString());
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else{
System.out.println("<");
}
}
}
}
else {
if(n1>n2) {
System.out.println(">");
}
else if(n1==n2) {
int one = Integer.parseInt(x1);
int two = Integer.parseInt(sb.toString());
if(one>two) {
System.out.println(">");
}
else if(one==two) {
System.out.println("=");
}
else{
System.out.println("<");
}
}
else {
System.out.println("<");
}
}
}
}
}
static void ruffleSort(int a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
int temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
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 a sequence a_1, a_2, ..., a_n consisting of n pairwise distinct positive integers.
Find \left⌊ \frac n 2 \right⌋ different pairs of integers x and y such that:
* x ≠ y;
* x and y appear in a;
* x~mod~y doesn't appear in a.
Note that some x or y can belong to multiple pairs.
⌊ x ⌋ denotes the floor function — the largest integer less than or equal to x. x~mod~y denotes the remainder from dividing x by y.
If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.
The first line of each testcase contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6).
All numbers in the sequence are pairwise distinct. The sum of n over all testcases doesn't exceed 2 ⋅ 10^5.
Output
The answer for each testcase should contain \left⌊ \frac n 2 \right⌋ different pairs of integers x and y such that x ≠ y, x and y appear in a and x~mod~y doesn't appear in a. Print the pairs one after another.
You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is x and the second number is y. All pairs should be pairwise distinct.
If there are multiple solutions, print any of them.
Example
Input
4
2
1 4
4
2 8 3 4
5
3 8 5 9 7
6
2 7 5 3 4 8
Output
4 1
8 2
8 4
9 5
7 5
8 7
4 3
5 2
Note
In the first testcase there are only two pairs: (1, 4) and (4, 1). \left⌊ \frac 2 2 \right⌋=1, so we have to find one pair. 1~mod~4=1, and 1 appears in a, so that pair is invalid. Thus, the only possible answer is a pair (4, 1).
In the second testcase, we chose pairs 8~mod~2=0 and 8~mod~4=0. 0 doesn't appear in a, so that answer is valid. There are multiple possible answers for that testcase.
In the third testcase, the chosen pairs are 9~mod~5=4 and 7~mod~5=2. Neither 4, nor 2, appears in a, so that answer is valid. | #include <bits/stdc++.h>
using namespace std;
void solve() {
long long int n, i;
cin >> n;
long long int a[n];
for (i = 0; i < n; i++) cin >> a[i];
;
sort(a, a + n);
for (i = 1; i < n / 2 + 1; i++) cout << a[i] << " " << a[0] << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin >> t;
while (t--) solve();
}
|
Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts 100^{500} seconds, during which Monocarp attacks the dragon with a poisoned dagger. The i-th attack is performed at the beginning of the a_i-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals 1 damage during each of the next k seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).
For example, suppose k = 4, and Monocarp stabs the dragon during the seconds 2, 4 and 10. Then the poison effect is applied at the start of the 2-nd second and deals 1 damage during the 2-nd and 3-rd seconds; then, at the beginning of the 4-th second, the poison effect is reapplied, so it deals exactly 1 damage during the seconds 4, 5, 6 and 7; then, during the 10-th second, the poison effect is applied again, and it deals 1 damage during the seconds 10, 11, 12 and 13. In total, the dragon receives 10 damage.
Monocarp knows that the dragon has h hit points, and if he deals at least h damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of k (the number of seconds the poison effect lasts) that is enough to deal at least h damage to the dragon.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of the test case contains two integers n and h (1 ≤ n ≤ 100; 1 ≤ h ≤ 10^{18}) — the number of Monocarp's attacks and the amount of damage that needs to be dealt.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9; a_i < a_{i + 1}), where a_i is the second when the i-th attack is performed.
Output
For each test case, print a single integer — the minimum value of the parameter k, such that Monocarp will cause at least h damage to the dragon.
Example
Input
4
2 5
1 5
3 10
2 4 10
5 3
1 2 4 5 7
4 1000
3 25 64 1337
Output
3
4
1
470
Note
In the first example, for k=3, damage is dealt in seconds [1, 2, 3, 5, 6, 7].
In the second example, for k=4, damage is dealt in seconds [2, 3, 4, 5, 6, 7, 10, 11, 12, 13].
In the third example, for k=1, damage is dealt in seconds [1, 2, 4, 5, 7]. | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long int llINF = (long long)(1e18) + 100;
const int MAXN = 4e5 + 10;
long long int n, a[200], h;
bool test(long long int val) {
long long int hp = h;
for (int i = 0; i < n - 1; i++) {
long long int aux = min(val, a[i + 1] - a[i]);
hp -= aux;
if (hp <= 0) return true;
}
return hp <= val;
}
void solve() {
cin >> n >> h;
for (int i = 0; i < n; i++) cin >> a[i];
long long int ini = 1, fim = llINF, bst = llINF;
while (ini <= fim) {
long long int meio = (ini + fim) / 2;
if (test(meio)) {
bst = meio;
fim = meio - 1;
} else
ini = meio + 1;
}
cout << bst << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin >> T;
while (T--) solve();
}
|
Let's call a sequence of integers x_1, x_2, ..., x_k MEX-correct if for all i (1 ≤ i ≤ k) |x_i - \operatorname{MEX}(x_1, x_2, ..., x_i)| ≤ 1 holds. Where \operatorname{MEX}(x_1, ..., x_k) is the minimum non-negative integer that doesn't belong to the set x_1, ..., x_k. For example, \operatorname{MEX}(1, 0, 1, 3) = 2 and \operatorname{MEX}(2, 1, 5) = 0.
You are given an array a consisting of n non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo 998244353.
Note: a subsequence of an array a is a sequence [a_{i_1}, a_{i_2}, ..., a_{i_m}] meeting the constraints 1 ≤ i_1 < i_2 < ... < i_m ≤ n. If two different ways to choose the sequence of indices [i_1, i_2, ..., i_m] yield the same subsequence, the resulting subsequence should be counted twice (i. e. two subsequences are different if their sequences of indices [i_1, i_2, ..., i_m] are not the same).
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ n).
The sum of n over all test cases doesn't exceed 5 ⋅ 10^5.
Output
For each test case, print a single integer — the number of non-empty MEX-correct subsequences of a given array, taken modulo 998244353.
Example
Input
4
3
0 2 1
2
1 0
5
0 0 0 0 0
4
0 1 2 3
Output
4
2
31
7
Note
In the first example, the valid subsequences are [0], [1], [0,1] and [0,2].
In the second example, the valid subsequences are [0] and [1].
In the third example, any non-empty subsequence is valid. |
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import javax.security.auth.login.AccountExpiredException;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
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;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum(long mod , long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static long pow[];
static void TEST_CASE() {
mod = 998244353 ;
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0 ;i<n ; i++)
arr[i] = sc.nextInt();
pow = new long[n+10];
pow[0] = 1;
for(int i = 1 ; i<pow.length ; i++) {
pow[i] = (pow[i-1]*2)%mod;
}
long[] mexg = new long[n+10];
long[] mexs = new long[n+10];
int c1 = 0 , c0 = 0;
long tot = 0;
for(int e:arr) {
if(e == 0) {
c0 ++;
mexs[1] = (pow[c0]-1 + mod )%mod;
mexg[1] = (mexg[1] + mexg[1])%mod;
}else if(e == 1) {
c1++;
// mex == 0
mexg[0] = (pow[c1]-1 + mod )%mod;
// mex == 2
mexs[2] = (mexs[2] + mexs[2] + mexs[1] )%mod;
mexg[2] = (mexg[2] + mexg[2] )%mod;
}else {
// for 3
// mex == 2
mexg[e-1] = (mexg[e-1] + mexg[e-1] + mexs[e-1] )%mod;
// mex == 4
mexs[e+1] = (mexs[e+1] +mexs[e+1]+ mexs[e])%mod;
mexg[e+1] = (mexg[e+1] + mexg[e+1])%mod;
}
// System.out.println("------------"+e+"-------------------");
// for(int i = 0 ; i<5 ; i++) {
// System.out.println(i + " - "+mexs[i] +" "+mexg[i]);
// }
}
for(long e:mexs) tot = (tot + e)%mod;
for(long e:mexg) tot = (tot + e)%mod;
sb.append(tot+"\n");
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
There is a grid, consisting of n rows and m columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked.
A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: "move right", "move down", "move left" or "move up". Each command means moving to a neighbouring cell in the corresponding direction.
However, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing.
We want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
The first line of each testcase contains two integers n and m (1 ≤ n, m ≤ 10^6; n ⋅ m ≤ 10^6) — the number of rows and the number of columns in the grid.
The i-th of the next n lines provides a description of the i-th row of the grid. It consists of m elements of one of three types:
* '.' — the cell is free;
* '#' — the cell is blocked;
* 'L' — the cell contains a lab.
The grid contains exactly one lab. The sum of n ⋅ m over all testcases doesn't exceed 10^6.
Output
For each testcase find the free cells that the robot can be forced to reach the lab from. Given the grid, replace the free cells (marked with a dot) with a plus sign ('+') for the cells that the robot can be forced to reach the lab from. Print the resulting grid.
Example
Input
4
3 3
...
.L.
...
4 5
#....
..##L
...#.
.....
1 1
L
1 9
....L..#.
Output
...
.L.
...
#++++
..##L
...#+
...++
L
++++L++#.
Note
In the first testcase there is no free cell that the robot can be forced to reach the lab from. Consider a corner cell. Given any direction, it will move to a neighbouring border grid that's not a corner. Now consider a non-corner free cell. No matter what direction you send to the robot, it can choose a different direction such that it ends up in a corner.
In the last testcase, you can keep sending the command that is opposite to the direction to the lab and the robot will have no choice other than move towards the lab. | # pylint: disable=unused-variable
# pylint: enable=too-many-lines
# * Just believe in yourself
# $ Author @CAP
# import numpy
import os
import sys
from io import BytesIO, IOBase
import math as M
import itertools as ITR
from collections import defaultdict as D
from collections import Counter as C
from collections import deque as Q
import threading
from functools import cmp_to_key, lru_cache, reduce
from functools import cmp_to_key as CMP
from bisect import bisect, bisect_left as BL
from bisect import bisect_right as BR
import random as R
import string
import cmath, time
from heapq import heapify, heappop as HPOP
from heapq import heappush as HPUSH
import heapq as H
enum = enumerate
start_time = time.time()
# * Variables
MOD = 1_00_00_00_007
MA = float("inf")
MI = float("-inf")
# * Graph 8 direction
d8i = (-1, -1, 0, 1, 1, 1, 0, -1); d8j = (0, 1, 1, 1, 0, -1, -1, -1)
# * Graph 4 direction
d4i = (-1, 0, 1, 0); d4j=(0, 1, 0, -1)
# * Stack increment
def increase_stack():
sys.setrecursionlimit(2 ** 32 // 2 - 1)
threading.stack_size(1 << 27)
# sys.setrecursionlimit(10**6)
# threading.stack_size(10**8)
# t = threading.Thread(target=main)
# t.start()
# t.join()
# * Region Funtions
def binary(n):
return bin(n)[2:]
def decimal(s):
return int(s, 2)
def pow2(n):
p = 0
while n > 1:
n //= 2
p += 1
return p
def maxfactor(n):
q = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
q.append(i)
if q:
return q[-1]
def factors(n):
q = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
q.append(i)
q.append(n // i)
return list(sorted(list(set(q))))
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(M.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
l.sort()
return l
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 seive(n):
a = []
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 = p + 1
for p in range(2, n + 1):
if prime[p]:
a.append(p)
prime[0] = prime[1] = False
return a, prime
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(M.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countchar(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 str_counter(a):
q = [0] * 26
for i in range(len(a)):
q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
return q
def lis(arr):
n = len(arr)
lis = [1] * n
maximum = 0
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 = max(maximum, lis[i])
return maximum
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def agcd(a, *b):
for i in b:
a = gcd(a, i)
return a
def lcm(a, *b):
val = a
gc = a
for i in b:
gc = gcd(gc, i)
val *= i
return val // gc
def ncr(n, r):
return M.factorial(n) // (M.factorial(n - r) * M.factorial(r))
def npr(n, r):
return M.factorial(n) // M.factorial(n - r)
# * Make work easy funtions
def IF(c, t, f):
return t if c else f
def YES(c):
print(IF(c, "YES", "NO"))
def Yes(c):
print(IF(c, "Yes", "No"))
def yes(c):
print(IF(c, "yes", "no"))
def JA(a, sep=" "):
print(sep.join(map(str, a)))
def JAA(a, s="\n", t=" "):
print(s.join(t.join(map(str, b)) for b in a))
def PS(a, s=" "):
print(str(a), end=s)
# * Region Taking Input
def I():
return int(inp())
def F():
return float(inp())
def LI():
return list(map(int, inp().split()))
def LF():
return list(map(float, inp().split()))
def MATI(n):
return [LI() for i in range(n)]
def MATS(n):
return [list(inp()) for i in range(n)]
def IV():
return map(int, inp().split())
def FV():
return map(float, inp().split())
def LS():
return list(inp())
def S():
return inp()
# * 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)
inp = lambda: sys.stdin.readline().rstrip("\r\n")
# @==================================== Write The Useful Code Here ============================
# @Make it one if there is some test cases
TestCases = 1 # @=====================
# @ =======================================
def bfs(grid,n,m,que):
while que:
x,y=que.popleft()
count=0
for i in range(4):
ni=x+d4i[i]; nj=y+d4j[i]
if ni<n and nj<m and ni>=0 and nj>=0 and grid[ni][nj]=='.' :
count+=1
if count==1 or count==0:
grid[x][y]="+"
for q in range(4):
ni=x+d4i[q]; nj=y+d4j[q]
if ni<n and nj<m and ni>=0 and nj>=0 and grid[ni][nj]=='.':
que.append((ni,nj))
def solve(test_no):
n,m=IV()
grid=[]
for i in range(n):
q=LS()
grid.append(q)
que=Q()
for i in range(n):
for j in range(m):
if grid[i][j]=='L':
for q in range(4):
ni=i+d4i[q]; nj=j+d4j[q]
if ni<n and nj<m and ni>=0 and nj>=0 and grid[ni][nj]=='.':
que.append((ni,nj))
bfs(grid,n,m,que)
break
for i in range(n):
print("".join(grid[i]))
# < This is the Main Function
def main():
flag = 1
#< Checking we are offline or not
try:
sys.stdin = open(
"C:/Users/raavi.manoj/Documents/coding/python/input.txt",
"r",
)
sys.stdout = open(
"C:/Users/raavi.manoj/Documents/coding/python/output.txt",
"w",
)
except:
flag = 0
t = 1
if TestCases:
t = I()
for test in range(1, t + 1):
solve(test)
if flag:
print("\nTHIS IS A PYTHON OUTPUT FILE")
print("Time: %.4f seconds" % (time.time() - start_time))
localtime = time.asctime(time.localtime(time.time()))
print(localtime)
sys.stdout.close()
# < End Region
if __name__ == "__main__":
# ? Incresing Stack Limit
# increase_stack()
#< Calling Main Function
main()
|
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is the vertex 1.
You have to color all vertices of the tree into n colors (also numbered from 1 to n) so that there is exactly one vertex for each color. Let c_i be the color of vertex i, and p_i be the parent of vertex i in the rooted tree. The coloring is considered beautiful if there is no vertex k (k > 1) such that c_k = c_{p_k} - 1, i. e. no vertex such that its color is less than the color of its parent by exactly 1.
Calculate the number of beautiful colorings, and print it modulo 998244353.
Input
The first line contains one integer n (2 ≤ n ≤ 250000) — the number of vertices in the tree.
Then n-1 lines follow, the i-th line contains two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) denoting an edge between the vertex x_i and the vertex y_i. These edges form a tree.
Output
Print one integer — the number of beautiful colorings, taken modulo 998244353.
Examples
Input
5
1 2
3 2
4 2
2 5
Output
42
Input
5
1 2
2 3
3 4
4 5
Output
53
Input
20
20 19
20 4
12 4
5 8
1 2
20 7
3 10
7 18
11 8
9 10
17 10
1 15
11 16
14 11
18 10
10 1
14 2
13 17
20 6
Output
955085064 | #include <bits/stdc++.h>
using namespace std;
const int G = 3;
const int Gi = 332748118;
long long su(long long a, long long b) {
a += b;
return (a >= 998244353) ? a - 998244353 : a;
}
int r[300000], lim;
long long ksm(long long a, long long p) {
long long res = 1;
while (p) {
if (p & 1) {
res = res * a % 998244353;
}
a = a * a % 998244353;
p >>= 1;
}
return res;
}
void ntt(vector<long long> &A, int type) {
for (int i = 0; i <= lim - 1; ++i) {
if (i < r[i]) swap(A[i], A[r[i]]);
}
for (int mid = 1; mid <= lim - 1; mid <<= 1) {
long long Wn = ksm(type == 1 ? G : Gi, (998244353 - 1) / (mid << 1));
for (int j = 0; j <= lim - 1; j += (mid << 1)) {
long long w = 1;
for (int k = 0; k <= mid - 1; ++k, w = (w * Wn) % 998244353) {
int x = A[j + k];
int y = w * A[j + mid + k] % 998244353;
A[j + k] = su(x, y);
A[j + mid + k] = su(x, 998244353 - y);
}
}
}
if (type == -1) {
long long tmp = ksm(lim, 998244353 - 2);
for (int i = 0; i <= lim - 1; ++i) {
A[i] = A[i] * tmp % 998244353;
}
}
}
vector<long long> operator*(vector<long long> A, vector<long long> B) {
int len = A.size() + B.size() - 1;
lim = 1;
while (lim <= len) lim <<= 1;
for (int i = 0; i <= lim - 1; ++i) {
r[i] = (r[i >> 1] >> 1) | ((i & 1) * (lim >> 1));
}
A.resize(lim);
B.resize(lim);
ntt(A, 1);
ntt(B, 1);
for (int i = 0; i <= lim - 1; ++i) {
A[i] = A[i] * B[i] % 998244353;
}
ntt(A, -1);
A.resize(len);
return A;
}
int i, j, k, n, m, t, a[250005];
long long jc[250005];
vector<long long> v;
vector<long long> work(int l, int r) {
if (l == r) {
return {1, a[l] - (l != 1)};
}
return work(l, (l + r) / 2) * work((l + r) / 2 + 1, r);
}
int main() {
jc[0] = 1;
for (i = 1; i <= 250000; i++) {
jc[i] = jc[i - 1] * i % 998244353;
}
ios::sync_with_stdio(0);
cin >> n;
for (i = 1; i < n; i++) {
cin >> j >> k;
a[j]++;
a[k]++;
}
v = work(1, n);
long long res = 0;
for (i = n - 1; i >= 0; i--) {
if (i & 1)
res = su(res, 998244353 - v[i] * jc[n - i] % 998244353);
else
res = su(res, v[i] * jc[n - i] % 998244353);
}
cout << res;
}
|
There are n block towers in a row, where tower i has a height of a_i. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:
* Choose two indices i and j (1 ≤ i, j ≤ n; i ≠ j), and move a block from tower i to tower j. This essentially decreases a_i by 1 and increases a_j by 1.
You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as max(a)-min(a).
What's the minimum possible ugliness you can achieve, after any number of days?
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t cases follow.
The first line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of buildings.
The second line of each test case contains n space separated integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^7) — the heights of the buildings.
Output
For each test case, output a single integer — the minimum possible ugliness of the buildings.
Example
Input
3
3
10 10 10
4
3 2 1 2
5
1 2 3 1 5
Output
0
0
1
Note
In the first test case, the ugliness is already 0.
In the second test case, you should do one operation, with i = 1 and j = 3. The new heights will now be [2, 2, 2, 2], with an ugliness of 0.
In the third test case, you may do three operations:
1. with i = 3 and j = 1. The new array will now be [2, 2, 2, 1, 5],
2. with i = 5 and j = 4. The new array will now be [2, 2, 2, 2, 4],
3. with i = 5 and j = 3. The new array will now be [2, 2, 3, 2, 3].
The resulting ugliness is 1. It can be proven that this is the minimum possible ugliness for this test. | # -*- coding: UTF-8 -*-
t = int(input())
inputdata = []
for i in range(t):
input()
inputdata.append(input().split(" "))
for j in range(len(inputdata[i])):
inputdata[i][j] = int(inputdata[i][j])
for i in range(t):
res = 0
l = len(inputdata[i])
ost = sum(inputdata[i]) % l
while(ost > 0):
ost -= l;
res += 1
print(res)
|
You are given an array consisting of all integers from [l, r] inclusive. For example, if l = 2 and r = 5, the array would be [2, 3, 4, 5]. What's the minimum number of elements you can delete to make the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the array non-zero?
A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t cases follow.
The first line of each test case contains two integers l and r (1 ≤ l ≤ r ≤ 2 ⋅ 10^5) — the description of the array.
Output
For each test case, output a single integer — the answer to the problem.
Example
Input
5
1 2
2 8
4 5
1 5
100000 200000
Output
1
3
0
2
31072
Note
In the first test case, the array is [1, 2]. Currently, the bitwise AND is 0, as 1\ \& \ 2 = 0. However, after deleting 1 (or 2), the array becomes [2] (or [1]), and the bitwise AND becomes 2 (or 1). This can be proven to be the optimal, so the answer is 1.
In the second test case, the array is [2, 3, 4, 5, 6, 7, 8]. Currently, the bitwise AND is 0. However, after deleting 4, 5, and 8, the array becomes [2, 3, 6, 7], and the bitwise AND becomes 2. This can be proven to be the optimal, so the answer is 3. Note that there may be other ways to delete 3 elements. | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int l = in.nextInt();
int r = in.nextInt();
int ans = r - l;
for (int bit = 0; bit < 30; bit++) {
ans = Math.min(ans, f(r, bit) - f(l - 1, bit));
}
out.println(ans);
}
}
private int f(int n, int i) {
// Among the numbers [0, n], how many have bit zero in position i?
int blockSize = 1 << i;
int blockId = n / blockSize;
int offset = n % blockSize;
int res = (blockId + 1) / 2 * blockSize;
if (blockId % 2 == 0) {
res += offset + 1;
}
return res;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
try {
in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
} catch (Exception e) {
throw new AssertionError();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
There are n candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string s, where the i-th candle is lit if and only if s_i=1.
<image>
Initially, the candle lights are described by a string a. In an operation, you select a candle that is currently lit. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).
You would like to make the candles look the same as string b. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.
Input
The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. Then t cases follow.
The first line of each test case contains a single integer n (1≤ n≤ 10^5) — the number of candles.
The second line contains a string a of length n consisting of symbols 0 and 1 — the initial pattern of lights.
The third line contains a string b of length n consisting of symbols 0 and 1 — the desired pattern of lights.
It is guaranteed that the sum of n does not exceed 10^5.
Output
For each test case, output the minimum number of operations required to transform a to b, or -1 if it's impossible.
Example
Input
5
5
11010
11010
2
01
11
3
000
101
9
100010111
101101100
9
001011011
011010101
Output
0
1
-1
3
4
Note
In the first test case, the two strings are already equal, so we don't have to perform any operations.
In the second test case, we can perform a single operation selecting the second candle to transform 01 into 11.
In the third test case, it's impossible to perform any operations because there are no lit candles to select.
In the fourth test case, we can perform the following operations to transform a into b:
1. Select the 7-th candle: 100010{\color{red}1}11→ 011101{\color{red} 1}00.
2. Select the 2-nd candle: 0{\color{red} 1}1101100→ 1{\color{red} 1}0010011.
3. Select the 1-st candle: {\color{red}1}10010011→ {\color{red}1}01101100.
In the fifth test case, we can perform the following operations to transform a into b:
1. Select the 6-th candle: 00101{\color{red}1}011→ 11010{\color{red}1}100
2. Select the 2-nd candle: 1{\color{red}1}0101100→ 0{\color{red}1}1010011
3. Select the 8-th candle: 0110100{\color{red}1}1→ 1001011{\color{red}1}0
4. Select the 7-th candle: 100101{\color{red}1}10→ 011010{\color{red}1}01 | // हर हर महादेव
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
public final class Solution {
static int inf = Integer.MAX_VALUE;
static long mod = 1000000000 + 7;
static void ne(Scanner sc, BufferedWriter op) throws Exception {
int n=sc.nextInt();
String one=sc.next();
String two=sc.next();
int _10=0;
int _00=0;
int _11=0;
int _01=0;
for(int i=0;i<n;i++){
int c1=one.charAt(i)-'0';
int c2=two.charAt(i)-'0';
if(c1==0 && c2==0){
_00++;
}
if(c1==1 && c2==0){
_10++;
}
if(c1==1 && c2==1){
_11++;
}
if(c1==0 && c2==1){
_01++;
}
}
int same=_00+_11;
int diff=_01+_10;
if(same==n){
op.write("0\n");
return;
}
if(same==1 && _11==1){
op.write("1\n");
return;
}
// if(diff==n){
// if(diff%2==0){
// op.write(n+"\n");
// }else{
// op.write("-1\n");
// }
// return;
// }
int ans=inf;
if(_11-_00==1 && _00!=0 && _11!=0){
// print("here");
ans=Math.min(ans,same);
}
if(_10 ==_01 && _10!=0 && _01!=0){
ans=Math.min(ans,diff);
}
if(ans==inf){
op.write("-1\n");
}else{
op.write(ans+"\n");
}
}
public static boolean ok(int n, int k)
{
if ((n & (1 << (k - 1))) > 0)
return true;
else
return false;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void main(String[] args) throws Exception {
BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out));
// Reader sc = new Reader();
Scanner sc= new Scanner(System.in);
int t = sc.nextInt();
while (t-->0){ ne(sc, op); }
// ne(sc,op);
op.flush();
}
static void print(Object o) {
System.out.println(String.valueOf(o));
}
static int[] toIntArr(String s){
int[] val= new int[s.length()];
for(int i=0;i<s.length();i++){
val[i]=s.charAt(i)-'a';
}
return val;
}
static void sort(int[] arr){
ArrayList<Integer> list= new ArrayList<>();
for(int i=0;i<arr.length;i++){
list.add(arr[i]);
}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i]=list.get(i);
}
}
static void sort(long[] arr){
ArrayList<Long> list= new ArrayList<>();
for(int i=0;i<arr.length;i++){
list.add(arr[i]);
}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i]=list.get(i);
}
}
}
// return -1 to put no ahed in array
class pair {
int xx;
int yy;
pair(int xx, int yy ) {
this.xx = xx;
this.yy = yy;
}
}
class sortY implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.yy > p2.yy) {
return 1;
} else if (p1.yy == p2.yy) {
if (p1.xx > p2.xx) {
return 1;
} else if (p1.xx < p2.xx) {
return -1;
}
return 0;
}
return -1;
}
}
class sortX implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.xx > p2.xx) {
return 1;
} else if (p1.xx == p2.xx) {
if (p1.yy > p2.yy) {
return 1;
} else if (p1.yy < p2.yy) {
return -1;
}
return 0;
}
return -1;
}
}
class debug {
static void print1d(long[] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
static void print1d(int[] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.println(i+" = "+arr[i]);
}
}
static void print1d(boolean[] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.println(i + "= " + arr[i]);
}
}
static void print2d(int[][] arr) {
System.out.println();
int n = arr.length;
int n2 = arr[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
static void print2d(boolean[][] arr) {
System.out.println();
int n = arr.length;
int n2 = arr[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
static void print2d(long[][] arr) {
System.out.println();
int n = arr.length;
int n2 = arr[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
static void printPair(ArrayList<pair> list) {
if(list.size()==0){
System.out.println("empty list");
return;
}
System.out.println();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).xx+"-"+list.get(i).yy);
}
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(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') {
if (cnt != 0) {
break;
} else {
continue;
}
}
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();
}
}
class MultiTreeSet<E> {
TreeMap<E, Integer> freqTreeMap = new TreeMap<E, Integer>();
int size;
public MultiTreeSet() {}
public MultiTreeSet(Collection<? extends E> c) {
for(E element : c)
add(element);
}
public int size() {
return size;
}
public void add(E element) {
Integer freq = freqTreeMap.get(element);
if(freq==null)
freqTreeMap.put(element, 1);
else
freqTreeMap.put(element,freq+1);
++size;
}
public void remove(E element) {
Integer freq = freqTreeMap.get(element);
if(freq!=null) {
if(freq==1)
freqTreeMap.remove(element);
else
freqTreeMap.put(element, freq-1);
--size;
}
}
public int get(E element) {
Integer freq = freqTreeMap.get(element);
if(freq==null)
return 0;
return freq;
}
public boolean contains(E element) {
return get(element)>0;
}
public boolean isEmpty() {
return size==0;
}
public E first() {
return freqTreeMap.firstKey();
}
public E last() {
return freqTreeMap.lastKey();
}
public E ceiling(E element) {
return freqTreeMap.ceilingKey(element);
}
public E floor(E element) {
return freqTreeMap.floorKey(element);
}
public E higher(E element) {
return freqTreeMap.higherKey(element);
}
public E lower(E element) {
return freqTreeMap.lowerKey(element);
}
}
|
'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are n nodes in the tree, connected by n-1 edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation.
<image>
He has m elves come over and admire his tree. Each elf is assigned two nodes, a and b, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of the values of the lights on the edges in that path.
However, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned (a_i, b_i), as well as the parity of the number of set bits in his favorite number. In other words, he remembers whether the number of 1's when his favorite number is written in binary is odd or even.
Help Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history!
Input
The first line contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t cases follow.
The first line of each test case contains two integers, n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the size of tree and the number of elves respectively.
The next n-1 lines of each test case each contains three integers, x, y, and v (1 ≤ x, y ≤ n; -1 ≤ v < 2^{30}) — meaning that there's an edge between nodes x and y. If
* v = -1: Santa doesn't remember what the set of lights were on for this edge.
* v ≥ 0: The set of lights on the edge is v.
The next m lines of each test case each contains three integers, a, b, and p (1 ≤ a, b ≤ n; a ≠ b; 0 ≤ p ≤ 1) — the nodes that the elf was assigned to, and the parity of the number of set bits in the elf's favorite number.
It is guaranteed that the sum of all n and the sum of all m don't exceed 2 ⋅ 10^5 each.
It is guaranteed that the given edges form a tree.
Output
For each test case, first print either YES or NO (in any case), whether there's a tree consistent with Santa's memory or not.
If the answer is YES, print n-1 lines each containing three integers: x, y, and v (1 ≤ x, y ≤ n; 0 ≤ v < 2^{30}) — the edge and the integer on that edge. The set of edges must be the same as in the input, and if the value of some edge was specified earlier, it can not change. You can print the edges in any order.
If there are multiple answers, print any.
Example
Input
4
6 5
1 2 -1
1 3 1
4 2 7
6 3 0
2 5 -1
2 3 1
2 5 0
5 6 1
6 1 1
4 5 1
5 3
1 2 -1
1 3 -1
1 4 1
4 5 -1
2 4 0
3 4 1
2 3 1
3 3
1 2 -1
1 3 -1
1 2 0
1 3 1
2 3 0
2 1
1 2 1
1 2 0
Output
YES
1 2 0
1 3 1
2 4 7
3 6 0
2 5 0
YES
1 2 1
1 3 0
1 4 1
4 5 1
NO
NO
Note
The first test case is the image in the statement.
One possible answer is assigning the value of the edge (1, 2) to 5, and the value of the edge (2, 5) to 3. This is correct because:
* The first elf goes from node 2 to node 3. This elf's favorite number is 4, so he remembers the value 1 (as 4 has an odd number of 1 bits in its binary representation).
* The second elf goes from node 2 to node 5. This elf's favorite number is 3, so he remembers the value 0 (as 3 has an even number of 1 bits in its binary representation).
* The third elf goes from node 5 to node 6. This elf's favorite number is 7, so he remembers the value 1 (as 7 has an odd number of 1 bits in its binary representation).
* The fourth elf goes from node 6 to node 1. This elf's favorite number is 1, so he remembers the value 1 (as 1 has an odd number of 1 bits in its binary representation).
* The fifth elf goes from node 4 to node 5. This elf's favorite number is 4, so he remembers the number 1 (as 4 has an odd number of 1 bits in its binary representation).
Note that there are other possible answers. | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class d {
static final int LOG=30;
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
/*
we can reassign all edge values to bit count % 2 without changing the problem.
and all new values we put in the tree can just be 0 or 1 since we either need
to keep or flip the existing parity. after this reduction we are given the xor
of various paths in the tree.
and of course:) we may reduce xor(a,b) to xor(a,root) ^ xor(b,root)
where xor(i,j) is xor of elements on the path from i to j
once we have a bunch of equations we can determine all the values
xor(root,i) for all i
from which we can determine the values on the actual edges:)
*/
int t=scan.nextInt();
t:for(int tt=0;tt<t;tt++) {
int n=scan.nextInt(), m=scan.nextInt();
parent=new int[LOG][n];
xor=new int[LOG][n];
a=new ArrayList[n];
int[][] orig=new int[n-1][3];
for(int i=0;i<n;i++) a[i]=new ArrayList<>();
for(int i=0;i<n-1;i++) {
int u=scan.nextInt()-1, v=scan.nextInt()-1;
int val=scan.nextInt();
orig[i][0]=u;
orig[i][1]=v;
orig[i][2]=val;
if(val!=-1) val=Integer.bitCount(val)%2;
a[u].add(new edge(v,val));
a[v].add(new edge(u,val));
}
init(0,-1);
parent[0][0]=xor[0][0]=-1;
for(int j=1;j<LOG;j++) {
for(int i=0;i<n;i++) {
if(parent[j-1][i]==-1) parent[j][i]=-1;//-1=doesn't exist
else parent[j][i]=parent[j-1][parent[j-1][i]];
if(xor[j-1][i]==-1) xor[j][i]=-1;//-1=unknown
else if(parent[j-1][i]==-1||xor[j-1][parent[j-1][i]]==-1) xor[j][i]=-1;
else xor[j][i]=xor[j-1][i]^xor[j-1][parent[j-1][i]];
}
}
ArrayDeque<Integer> priority=new ArrayDeque<>();
r=new ArrayList[n];
for(int i=0;i<n;i++) r[i]=new ArrayList<>();
rvals=new int[n];
for(int i=0;i<n;i++) {
rvals[i]=getrval(i);
if(rvals[i]!=-1) priority.offer(i);
}
seen=new boolean[n];
for(int i=0;i<m;i++) {
int u=scan.nextInt()-1, v=scan.nextInt()-1, val=scan.nextInt();
r[u].add(new edge(v,val));
r[v].add(new edge(u,val));
}
for(int i=0;i<n-1;i++) {
if(orig[i][2]==-1) continue;
int val=Integer.bitCount(orig[i][2])%2;
int u=orig[i][0], v=orig[i][1];
r[u].add(new edge(v,val));
r[v].add(new edge(u,val));
}
while(!priority.isEmpty()) {
int i=priority.poll();
if(!seen[i]) {
if(!dfs(i)) {
out.println("NO");
continue t;
}
}
}
for(int i=0;i<n;i++) {
if(!seen[i]) {
rvals[i]=0;
if(!dfs(i)) {
out.println("NO");
continue t;
}
}
}
// System.out.println(Arrays.toString(rvals));
out.println("YES");
for(int i=0;i<n-1;i++) {
int u=orig[i][0], v=orig[i][1];
int val=orig[i][2];
if(val==-1) {
val=rvals[u]^rvals[v];
}
out.println((u+1)+" "+(v+1)+" "+val);
}
}
out.close();
}
public static boolean dfs(int at) {
boolean res=true;
seen[at]=true;
for(edge nxt:r[at]) {
int target=rvals[at]^nxt.val;
if(rvals[nxt.v]!=-1&&rvals[nxt.v]!=target) return false;
if(seen[nxt.v]) continue;
rvals[nxt.v]=target;
res&=dfs(nxt.v);
}
return res;
}
public static int getrval(int cur) {
int res=0;
for(int j=LOG-1;j>=0;j--) {
if(parent[j][cur]!=-1) {
if(xor[j][cur]==-1) return -1;
res^=xor[j][cur];
cur=parent[j][cur];
}
}
return res;
}
static boolean[] seen;
static int[] rvals;
static ArrayList<edge>[] a,r;
static int[][] parent,xor;
public static void init(int at, int prev) {
for(edge nxt:a[at]) {
if(nxt.v==prev) continue;
parent[0][nxt.v]=at;
xor[0][nxt.v]=nxt.val;
init(nxt.v,at);
}
}
static class edge {
int v,val;
edge(int v, int val) {
this.v=v;
this.val=val;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
}
/*
break case
1
5 2
1 2 -1
2 3 -1
3 4 1
4 5 -1
1 4 0
3 5 1
*/ |
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.
The game works as follows: there is a tree of size n, rooted at node 1, where each node is initially white. Red and Blue get one turn each. Red goes first.
In Red's turn, he can do the following operation any number of times:
* Pick any subtree of the rooted tree, and color every node in the subtree red.
However, to make the game fair, Red is only allowed to color k nodes of the tree. In other words, after Red's turn, at most k of the nodes can be colored red.
Then, it's Blue's turn. Blue can do the following operation any number of times:
* Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon.
Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.
After the two turns, the score of the game is determined as follows: let w be the number of white nodes, r be the number of red nodes, and b be the number of blue nodes. The score of the game is w ⋅ (r - b).
Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?
Input
The first line contains two integers n and k (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ n) — the number of vertices in the tree and the maximum number of red nodes.
Next n - 1 lines contains description of edges. The i-th line contains two space separated integers u_i and v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — the i-th edge of the tree.
It's guaranteed that given edges form a tree.
Output
Print one integer — the resulting score if both Red and Blue play optimally.
Examples
Input
4 2
1 2
1 3
1 4
Output
1
Input
5 2
1 2
2 3
3 4
4 5
Output
6
Input
7 2
1 2
1 3
4 2
3 5
6 3
6 7
Output
4
Input
4 1
1 2
1 3
1 4
Output
-1
Note
In the first test case, the optimal strategy is as follows:
* Red chooses to color the subtrees of nodes 2 and 3.
* Blue chooses to color the subtree of node 4.
At the end of this process, nodes 2 and 3 are red, node 4 is blue, and node 1 is white. The score of the game is 1 ⋅ (2 - 1) = 1.
In the second test case, the optimal strategy is as follows:
* Red chooses to color the subtree of node 4. This colors both nodes 4 and 5.
* Blue does not have any options, so nothing is colored blue.
At the end of this process, nodes 4 and 5 are red, and nodes 1, 2 and 3 are white. The score of the game is 3 ⋅ (2 - 0) = 6.
For the third test case:
<image>
The score of the game is 4 ⋅ (2 - 1) = 4. | #include <bits/stdc++.h>
using namespace std;
void solve();
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
const int inf = 2e9;
const long long linf = 2e18;
const long long mod = 998244353;
const int N = 2e5 + 100;
vector<int> g[N];
struct Elem {
int value, node, pos;
};
Elem merge(Elem a, Elem b) {
if (a.value < b.value)
return b;
else
return a;
}
struct T {
vector<Elem> t;
vector<int> u;
T(const vector<Elem> &a) {
t.assign(4 * a.size(), {0, 0});
u.assign(4 * a.size(), 0);
build(a, 0, 0, a.size());
}
void build(const vector<Elem> &a, int v, int l, int r) {
if (r - l == 1) {
t[v] = a[l];
return;
}
build(a, v * 2 + 1, l, (l + r) >> 1);
build(a, v * 2 + 2, (l + r) >> 1, r);
t[v] = merge(t[v * 2 + 1], t[v * 2 + 2]);
}
void push(int v, int l, int r) {
if (r - l == 1) {
t[v].value += u[v];
u[v] = 0;
return;
}
t[v].value += u[v];
u[v * 2 + 1] += u[v];
u[v * 2 + 2] += u[v];
u[v] = 0;
}
Elem get(int v, int l, int r, int vl, int vr) {
push(v, l, r);
if (vl >= r || vr <= l) return {-inf, -1};
if (vl <= l && r <= vr) return t[v];
if (r - l == 1) {
return t[v];
}
return merge(get(v * 2 + 1, l, (l + r) >> 1, vl, vr),
get((v * 2 + 2), (l + r) >> 1, r, vl, vr));
}
void upd(int v, int l, int r, int vl, int vr, int d) {
push(v, l, r);
if (vl >= r || vr <= l) return;
if (vl <= l && r <= vr) {
u[v] += d;
push(v, l, r);
return;
}
int m = (l + r) >> 1;
upd(v * 2 + 1, l, m, vl, vr, d);
upd(v * 2 + 2, m, r, vl, vr, d);
t[v] = merge(t[v * 2 + 1], t[v * 2 + 2]);
}
};
vector<Elem> leaves;
pair<int, int> segments[N];
int par[N];
pair<int, int> dfs(int v, int depth = 1) {
if (g[v].size() == 1 && par[v] != -1) {
int pos = leaves.size();
leaves.push_back({depth, v, pos});
return {leaves.size() - 1, leaves.size() - 1};
}
for (auto u : g[v]) {
if (par[v] == u) continue;
par[u] = v;
auto [l, r] = dfs(u, depth + 1);
segments[v].first = min(segments[v].first, l);
segments[v].second = max(segments[v].second, r);
}
return segments[v];
}
int marked[N];
void solve() {
int n, k;
cin >> n >> k;
fill(par, par + n, -1);
for (int i = 0; i < n; i++) segments[i] = {inf, -inf};
for (int i = 0; i < n - 1; i++) {
int t1, t2;
cin >> t1 >> t2;
t1--;
t2--;
g[t1].push_back(t2);
g[t2].push_back(t1);
}
dfs(0);
T t(leaves);
int unmarked = n;
long long best = -1ll * (n / 2) * (n - n / 2);
for (int i = 1; i <= k; i++) {
if (i > leaves.size()) {
long long rmax = max((long long)leaves.size(), (long long)min(i, n / 2));
best = max(best, rmax * (n - rmax));
continue;
}
Elem e = t.get(0, 0, leaves.size(), 0, leaves.size());
t.upd(0, 0, leaves.size(), e.pos, e.pos + 1, -inf);
int v = e.node;
marked[v] = true;
unmarked--;
v = par[v];
while (!marked[v]) {
marked[v] = true;
unmarked--;
t.upd(0, 0, leaves.size(), segments[v].first, segments[v].second + 1, -1);
if (par[v] == -1) break;
v = par[v];
}
long long bmax = min(n / 2, unmarked);
best = max(best, 1ll * i * (n - i) - bmax * (n - bmax));
}
cout << best << "\n";
}
|
After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height 1 and length n, some positions of which are occupied by 1 by 1 Lego pieces.
In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.
You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend 0 seconds).
The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo 1 000 000 007 (10^9 + 7).
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t cases follow.
The first line of each test case contains one integer n (2 ≤ n ≤ 2000) — the size of the Lego strip.
The second line of each test case contains a string s of length n, consisting of the characters 0, 1, and ? — your memory of the starting state:
* 1 represents a position that definitely has a Lego piece,
* 0 represents a position that definitely does not have a Lego piece,
* and ? represents a position that you don't remember.
The third line of each test case contains a string t of length n, consisting of the characters 0, 1, and ? — your memory of the ending state. It follows a similar format to the starting state.
It's guaranteed that the sum of n over all test cases doesn't exceed 2000.
Output
For each test case, output a single integer — the answer to the problem modulo 1 000 000 007 (10^9 + 7).
Example
Input
6
2
00
11
3
???
???
3
??1
0?0
4
??0?
??11
5
?????
0??1?
10
?01??01?1?
??100?1???
Output
1
16
1
14
101
1674
Note
For the first test case, 00 is the only possible starting state, and 11 is the only possible ending state. It takes exactly one operation to change 00 to 11.
For the second test case, some of the possible starting and ending state pairs are:
* (000, 011) — takes 1 operation.
* (001, 100) — takes 2 operations.
* (010, 000) — takes 0 operations, as it's impossible to achieve the ending state. | #include <bits/stdc++.h>
using namespace std;
const long long P = 1e9 + 7;
const int N = 2005;
const long long INF = (1ll << 62) - 1;
const double pi = acos(-1);
mt19937 rng(time(0));
int T, n;
int f[N][N * 2], g[N][N * 2];
char s[N], t[N];
void revbit(char s[]) {
for (int i = 2; i <= n; i += 2)
if (s[i] != '?') s[i] = '0' + '1' - s[i];
}
void calc(int f[][N * 2], char s[], char t[]) {
f[0][n + 1] = 1;
for (int i = (1); i <= (n); ++i)
for (int j = (n + 1 - i); j <= (n + 1 + i); ++j) {
f[i][j] = ((s[i] != '1' && t[i] != '1') ? f[i - 1][j] : 0) % P;
(f[i][j] += (s[i] != '0' && t[i] != '0') ? f[i - 1][j] : 0) %= P;
(f[i][j] += (s[i] != '0' && t[i] != '1') ? f[i - 1][j - 1] : 0) %= P;
(f[i][j] += (s[i] != '1' && t[i] != '0') ? f[i - 1][j + 1] : 0) %= P;
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
cin >> n >> (s + 1) >> (t + 1);
revbit(s), revbit(t);
calc(f, s, t);
reverse(s + 1, s + n + 1), reverse(t + 1, t + n + 1);
calc(g, s, t);
int ans = 0;
for (int i = (1); i <= (n - 1); ++i)
for (int j = (n + 1 - i); j <= (n + 1 + i); ++j)
ans = (1ll * abs(n + 1 - j) * f[i][j] % P * g[n - i][n + n + 2 - j] +
ans) %
P;
cout << ans << endl;
for (int i = (0); i <= (n); ++i)
for (int j = (n + 1 - i); j <= (n + 1 + i); ++j) f[i][j] = g[i][j] = 0;
}
return 0;
}
|
You are given an array a consisting of n non-negative integers.
You have to replace each 0 in a with an integer from 1 to n (different elements equal to 0 can be replaced by different integers).
The value of the array you obtain is the number of integers k from 1 to n such that the following condition holds: there exist a pair of adjacent elements equal to k (i. e. there exists some i ∈ [1, n - 1] such that a_i = a_{i + 1} = k). If there are multiple such pairs for some integer k, this integer is counted in the value only once.
Your task is to obtain the array with the maximum possible value.
Input
The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in the array.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ min(n, 600)) — the elements of the array.
Output
Print n integers not less than 1 and not greater than n — the array with the maximum possible value you can obtain.
If there are multiple answers, print any of them.
Examples
Input
4
1 1 0 2
Output
1 1 2 2
Input
5
0 0 0 0 0
Output
3 1 1 3 3
Input
5
1 2 3 4 5
Output
1 2 3 4 5
Input
6
1 0 0 0 0 1
Output
1 2 3 3 1 1
Input
3
3 0 2
Output
3 2 2
Input
5
1 0 2 0 1
Output
1 2 2 1 1
Input
7
1 0 2 3 1 0 2
Output
1 2 2 3 1 1 2 | #include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
template <class A, class B>
bool smin(A &x, B &&y) {
if (y < x) {
x = y;
return true;
}
return false;
}
template <class A, class B>
bool smax(A &x, B &&y) {
if (x < y) {
x = y;
return true;
}
return false;
}
struct Edmonds {
int n, T{};
vector<vector<int>> graph;
vector<int> pa, p, used, base;
vector<int> toJoin;
explicit Edmonds(int n) : n(n), graph(n), pa(n, -1), p(n), used(n), base(n) {}
void add_edge(int v, int u) {
graph[v].push_back(u);
graph[u].push_back(v);
}
int getBase(int i) { return base[i] == i ? i : base[i] = getBase(base[i]); }
void mark_path(int v, int x, int b, vector<int> &path) {
for (; getBase(v) != b; v = p[x]) {
p[v] = x;
x = pa[v];
toJoin.push_back(v);
toJoin.push_back(x);
if (!used[x]) {
used[x] = ++T;
path.push_back(x);
}
}
}
bool go(int v) {
for (int x : graph[v]) {
int b;
int bv = getBase(v);
int bx = getBase(x);
if (bv == bx) {
continue;
}
if (used[x]) {
vector<int> path;
toJoin.clear();
if (used[bx] < used[bv]) {
mark_path(v, x, b = bx, path);
} else {
mark_path(x, v, b = bv, path);
}
for (int z : toJoin) {
base[getBase(z)] = b;
}
for (int z : path) {
if (go(z)) {
return true;
}
}
} else if (p[x] < 0) {
p[x] = v;
if (pa[x] < 0) {
for (int y; x >= 0; x = v) {
y = p[x];
v = pa[y];
pa[x] = y;
pa[y] = x;
}
return true;
}
if (!used[pa[x]]) {
used[pa[x]] = ++T;
if (go(pa[x])) {
return true;
}
}
}
}
return false;
}
void init_dfs() {
used.assign(n, 0);
p.assign(n, -1);
iota(base.begin(), base.end(), 0);
}
bool dfs(int root) {
used[root] = ++T;
return go(root);
}
int matching() {
int ans = 0;
init_dfs();
for (int i = 0; i < n; ++i) {
if (pa[i] < 0 && dfs(i)) {
ans++;
init_dfs();
}
}
return ans;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (auto &x : a) cin >> x;
vector<bool> have(n);
for (int i = 0; i + 1 < n; ++i) {
if (a[i] > 0 && a[i + 1] > 0 && a[i] == a[i + 1]) {
have[a[i] - 1] = true;
}
}
vector<pair<int, int>> gaps;
for (int i = 0; i < n; ++i) {
if (a[i] != 0) {
continue;
}
int j = i;
while (j < n && a[j] == 0) {
++j;
}
gaps.emplace_back(i - 1, j);
i = j;
}
vector<int> vid(n, -1);
int id = 0;
for (int i = 0; i < n; ++i) {
if (!have[i]) {
vid[i] = id++;
}
}
int ngap = int(gaps.size());
int nvs = id + ngap + 1;
Edmonds graph(nvs);
auto addEdge = [&](int u, int v) {
assert(0 <= u && u < nvs && 0 <= v && v < nvs && u != v);
graph.add_edge(u, v);
};
int cid = id;
for (auto [l, r] : gaps) {
int len = r - l - 1;
if (len % 2 == 0) {
if (l >= 0 && r < n) {
int x = vid[a[l] - 1];
int y = vid[a[r] - 1];
if (x >= 0 && y >= 0 && x != y) {
addEdge(x, y);
}
}
} else {
if (l >= 0) {
int x = vid[a[l] - 1];
if (x >= 0) {
addEdge(cid, x);
}
}
if (r < n) {
int y = vid[a[r] - 1];
if (y >= 0) {
addEdge(cid, y);
}
}
}
cid++;
}
graph.matching();
cid = id;
for (auto [l, r] : gaps) {
int len = r - l - 1;
if (len % 2 == 0) {
if (l >= 0 && r < n) {
int x = vid[a[l] - 1];
int y = vid[a[r] - 1];
if (x >= 0 && y >= 0 && x != y) {
if (!have[a[l] - 1] && !have[a[r] - 1]) {
int mt = graph.pa[x];
if (mt == y) {
a[l + 1] = a[l];
a[r - 1] = a[r];
have[a[l] - 1] = true;
have[a[r] - 1] = true;
}
}
}
}
} else {
if (l >= 0) {
int x = vid[a[l] - 1];
if (x >= 0) {
int mt = graph.pa[cid];
if (mt == x && !have[a[l] - 1]) {
a[l + 1] = a[l];
have[a[l] - 1] = true;
}
}
}
if (r < n) {
int y = vid[a[r] - 1];
if (y >= 0) {
int mt = graph.pa[cid];
if (mt == y && !have[a[r] - 1]) {
a[r - 1] = a[r];
have[a[r] - 1] = true;
}
}
}
}
cid++;
}
int ptr = 0;
for (int i = 0; i < n; ++i) {
if (a[i] != 0) {
continue;
}
int j = i;
while (j < n && a[j] == 0) {
++j;
}
int len = j - i;
int fr = i;
if (len % 2 == 1) {
a[fr++] = 1;
}
for (int cur = fr; cur < j; cur += 2) {
while (ptr < n && have[ptr]) {
++ptr;
}
if (ptr == n) {
a[cur] = a[cur + 1] = 1;
} else {
a[cur] = a[cur + 1] = ptr + 1;
have[ptr] = true;
}
}
i = j;
}
for (auto x : a) cout << x << ' ';
cout << '\n';
return 0;
}
|
There are n reindeer at the North Pole, all battling for the highest spot on the "Top Reindeer" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the "Top Reindeer" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer games, but they still give it the utmost importance.
Currently, the i-th reindeer has a score of a_i. You would like to influence the leaderboard with some operations. In an operation, you can choose a reindeer, and either increase or decrease his score by 1 unit. Negative scores are allowed.
You have m requirements for the resulting scores. Each requirement is given by an ordered pair (u, v), meaning that after all operations, the score of reindeer u must be less than or equal to the score of reindeer v.
Your task is to perform the minimum number of operations so that all requirements will be satisfied.
Input
The first line contains two integers n and m (2≤ n≤ 1000; 1≤ m≤ 1000) — the number of reindeer and requirements, respectively.
The second line contains n integers a_1,…, a_n (1≤ a_i≤ 10^9), where a_i is the current score of reindeer i.
The next m lines describe the requirements.
The i-th of these lines contains two integers u_i and v_i (1≤ u_i, v_i≤ n; u_i≠ v_i) — the two reindeer of the i-th requirement.
Output
Print n integers b_1,…, b_n (-10^{15}≤ b_i≤ 10^{15}), where b_i is the score of the i-th reindeer after all operations.
If there are multiple solutions achieving the minimum number of operations, you may output any.
We can prove that there is always an optimal solution such that |b_i|≤ 10^{15} for all i.
Examples
Input
7 6
3 1 4 9 2 5 6
1 2
2 3
3 4
4 5
5 6
6 7
Output
1 1 4 4 4 5 6
Input
4 6
6 5 8 2
3 1
4 1
3 2
1 2
2 3
3 1
Output
6 6 6 2
Input
10 18
214 204 195 182 180 176 176 172 169 167
1 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2
6 1
6 2
6 3
6 4
6 5
6 7
6 8
6 9
6 10
Output
204 204 195 182 180 167 176 172 169 167 | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 2005;
int n, m, s, t, cnt, x[Maxn], y[Maxn], dis[Maxn], head[Maxn], cur[Maxn],
a[Maxn];
bool vis[Maxn];
vector<int> G[Maxn];
struct edg {
int nxt, to, w;
} edge[2 * Maxn];
void add(int x, int y, int w) {
edge[++cnt] = (edg){head[x], y, w};
head[x] = cnt;
edge[++cnt] = (edg){head[y], x, 0};
head[y] = cnt;
}
queue<int> Qu;
bool bfs(void) {
memset(dis, 0, sizeof(int[n + 3]));
Qu.push(s);
while (!Qu.empty()) {
int u = Qu.front();
Qu.pop();
for (int i = head[u]; i; i = edge[i].nxt) {
int to = edge[i].to;
if (!dis[to] && to != s && edge[i].w) dis[to] = dis[u] + 1, Qu.push(to);
}
}
return dis[t];
}
int dfs(int u, int mini) {
if (!mini || u == t) return mini;
int w, used = 0;
for (int& i = cur[u]; i; i = edge[i].nxt) {
int to = edge[i].to;
if (dis[to] == dis[u] + 1 && edge[i].w) {
w = dfs(to, min(mini - used, edge[i].w));
used += w, edge[i].w -= w, edge[((i - 1) ^ 1) + 1].w += w;
if (used == mini) return used;
}
}
return used;
}
void dinic(void) {
while (bfs()) {
memcpy(cur, head, sizeof(int[n + 3]));
dfs(s, 0x3f3f3f3f);
}
}
void work(int L, int R, vector<int> Ve) {
if (L == R || Ve.size() <= 1) return;
int mid = (L + R) >> 1;
memset(head, 0, sizeof(int[n + 3]));
cnt = 0;
for (auto u : Ve) {
vis[u] = true;
if (a[u] <= mid)
add(u, t, 1);
else
add(s, u, 1);
}
for (int i = 1; i <= m; i++)
if (vis[x[i]] && vis[y[i]]) add(x[i], y[i], 0x3f3f3f3f);
memset(vis, 0, sizeof(bool[n + 3]));
dinic();
for (int i = head[s]; i; i = edge[i].nxt)
if (edge[i].w) Qu.push(edge[i].to), vis[edge[i].to] = true;
while (!Qu.empty()) {
int u = Qu.front();
Qu.pop();
for (int i = head[u]; i; i = edge[i].nxt) {
int to = edge[i].to;
if (!vis[to] && edge[i].w) Qu.push(to), vis[to] = true;
}
}
vector<int> V1, V2;
for (auto u : Ve)
if (vis[u])
a[u] = max(a[u], mid + 1), V2.push_back(u);
else
a[u] = min(a[u], mid), V1.push_back(u);
work(L, mid, V1), work(mid + 1, R, V2);
}
int main() {
scanf("%d%d", &n, &m);
s = n + 1, t = n + 2;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= m; i++)
scanf("%d%d", &x[i], &y[i]), G[x[i]].push_back(y[i]);
vector<int> V;
for (int i = 1; i <= n; i++) V.push_back(i);
work(1, 1e9, V);
for (int i = 1; i <= n; i++) printf("%d ", a[i]);
return 0;
}
|
You are given strings S and T, consisting of lowercase English letters. It is guaranteed that T is a permutation of the string abc.
Find string S', the lexicographically smallest permutation of S such that T is not a subsequence of S'.
String a is a permutation of string b if the number of occurrences of each distinct character is the same in both strings.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
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 a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a string S (1 ≤ |S| ≤ 100), consisting of lowercase English letters.
The second line of each test case contains a string T that is a permutation of the string abc. (Hence, |T| = 3).
Note that there is no limit on the sum of |S| across all test cases.
Output
For each test case, output a single string S', the lexicographically smallest permutation of S such that T is not a subsequence of S'.
Example
Input
7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc
Output
aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac
Note
In the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.
In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.
In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence. | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x =Integer.parseInt(scan.nextLine());
while(x-->0)
{
String s=scan.nextLine();
String t=scan.nextLine();
// System.out.println(s+" "+t);
int a[]= new int[26];
for(int i=0;i<26;i++)
{
a[i]=0;
}
for(int i=0;i<s.length();i++)
{
a[s.charAt(i)-'a']++;
}
// for(int i=0;i<26;i++)
//System.out.print(a[i]+" ");
String ans="";
for(int i=0;i<a[0];i++)
{
ans+="a";
}
if(a[0]==0)
{
for(int i=0;i<a[1];i++)
{
ans+="b";
}
for(int i=0;i<a[2];i++)
{
ans+="c";
}
}
else if(t.equals("abc"))
{
for(int i=0;i<a[2];i++)
{
ans+="c";
}
for(int i=0;i<a[1];i++)
{
ans+="b";
}
}
else if(t.equals("acb"))
{
for(int i=0;i<a[1];i++)
{
ans+="b";
}
for(int i=0;i<a[2];i++)
{
ans+="c";
}
}
else
{
for(int i=0;i<a[1];i++)
{
ans+="b";
}
for(int i=0;i<a[2];i++)
{
ans+="c";
}
}
for(int i=3;i<26;i++)
{
for(int j=0;j<a[i];j++)
ans+=(char)('a'+i);
}
System.out.println(ans);
}
}
}
/*aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac*/
|
Given a positive integer n. Find three distinct positive integers a, b, c such that a + b + c = n and \operatorname{gcd}(a, b) = c, where \operatorname{gcd}(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. Description of the test cases follows.
The first and only line of each test case contains a single integer n (10 ≤ n ≤ 10^9).
Output
For each test case, output three distinct positive integers a, b, c satisfying the requirements. If there are multiple solutions, you can print any. We can show that an answer always exists.
Example
Input
6
18
63
73
91
438
122690412
Output
6 9 3
21 39 3
29 43 1
49 35 7
146 219 73
28622 122661788 2
Note
In the first test case, 6 + 9 + 3 = 18 and \operatorname{gcd}(6, 9) = 3.
In the second test case, 21 + 39 + 3 = 63 and \operatorname{gcd}(21, 39) = 3.
In the third test case, 29 + 43 + 1 = 73 and \operatorname{gcd}(29, 43) = 1. | def main():
for _ in range(int(input())):
n = int(input())
if n%2 == 0:
print(2, n-2-1,1)
else:
n-=1
n=n//2
if n%2 ==0:
print(n-1,n+1,1)
else:
print(n-2,n+2,1)
main()
|
Paprika loves permutations. She has an array a_1, a_2, ..., a_n. She wants to make the array a permutation of integers 1 to n.
In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers i (1 ≤ i ≤ n) and x (x > 0), then perform a_i := a_i mod x (that is, replace a_i by the remainder of a_i divided by x). In different operations, the chosen i and x can be different.
Determine the minimum number of operations needed to make the array a permutation of integers 1 to n. If it is impossible, output -1.
A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Input
Each test contains 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 an integer n (1 ≤ n ≤ 10^5).
The second line of each test case contains n integers a_1, a_2, ..., a_n. (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum number of operations needed to make the array a permutation of integers 1 to n, or -1 if it is impossible.
Example
Input
4
2
1 7
3
1 5 4
4
12345678 87654321 20211218 23571113
9
1 2 3 4 18 19 5 6 7
Output
1
-1
4
2
Note
For the first test, the only possible sequence of operations which minimizes the number of operations is:
* Choose i=2, x=5. Perform a_2 := a_2 mod 5 = 2.
For the second test, it is impossible to obtain a permutation of integers from 1 to n. | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class hello{
static class Pair implements Comparable<Pair>{
long val;
long ind;
public Pair(long val,long ind)
{
this.val=val;
this.ind=ind;
}
public int compareTo(Pair o)
{
return Long.compare(this.val, o.val);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
try {
br=new BufferedReader(new FileReader("input.txt"));
PrintStream out= new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}
// Catch block to handle the exceptions
catch (Exception e) {
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;
}
}
static int computeXOR(int n)
{
// If n is a multiple of 4
if (n % 4 == 0)
return n;
// If n%4 gives remainder 1
if (n % 4 == 1)
return 1;
// If n%4 gives remainder 2
if (n % 4 == 2)
return n + 1;
// If n%4 gives remainder 3
return 0;
}
static long helper(List<Long> l,long k)
{
int length = l.size()-1;
long val = 0;
while(length>=0)
{
val+=2*(l.get(length));
length-=k;
}
return val;
}
static long findGCD(long a, long b){
if(b == 0)
return a;
return findGCD(b, a%b);
}
public static void main (String[] args) throws java.lang.Exception
{
try{
FastReader sc=new FastReader();
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
long arr[] = new long[n];
HashMap<Long,Integer> map = new HashMap<>();
for(int i=0;i<n;i++)
{
arr[i] = sc.nextLong();
if(map.containsKey(arr[i]))
{
int c = map.get(arr[i]);
map.put(arr[i],c+1);
}
else
{
map.put(arr[i],1);
}
}
PriorityQueue<Long> pq = new PriorityQueue<>();
for(int i=0;i<n;i++)
{
long k = i+1;
if(map.containsKey(k))
{
int c = map.get(k);
if(c==1)
map.remove(k);
else
{
map.put(k,c-1);
}
}
else
{
pq.add(k);
}
}
PriorityQueue<Long> pq2 = new PriorityQueue<>();
for(long key:map.keySet())
{
int c = map.get(key);
while(c-->0)
{
pq2.add(key);
}
}
int count = 0;
boolean isTrue = true;
while(pq2.size()!=0&&pq.size()!=0)
{
long val1 = pq2.remove();
long val2 = pq.remove();
long h = val1-val2;
if(val2%h==val2)
{
count++;
}
else
{
isTrue=false;
break;
}
}
if(isTrue)
{
System.out.println(count);
}
else
{
System.out.println(-1);
}
}
}catch(Exception e){
return;
}
}
} |
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.
There are n players labelled from 1 to n. It is guaranteed that n is a multiple of 3.
Among them, there are k impostors and n-k crewmates. The number of impostors, k, is not given to you. It is guaranteed that n/3 < k < 2n/3.
In each question, you can choose three distinct integers a, b, c (1 ≤ a, b, c ≤ n) and ask: "Among the players labelled a, b and c, are there more impostors or more crewmates?" You will be given the integer 0 if there are more impostors than crewmates, and 1 otherwise.
Find the number of impostors k and the indices of players that are impostors after asking at most n+6 questions.
The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any 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 and only line of each test case contains a single integer n (6 ≤ n < 10^4, n is a multiple of 3) — the number of players.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^4.
Interaction
For each test case, the interaction starts with reading n.
Then you are allowed to make at most n+6 questions in the following way:
"? a b c" (1 ≤ a, b, c ≤ n, a, b and c are pairwise distinct).
After each one, you should read an integer r, which is equal to 0 if there are more impostors than crewmates among players labelled a, b and c, and equal to 1 otherwise.
Answer -1 instead of 0 or 1 means that you made an invalid query. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
When you have found the indices of all impostors, print a single line "! " (without quotes), followed by the number of impostors k, followed by k integers representing the indices of the impostors. Please note that you must print all this information on the same line.
After printing the answer, your program must then continue to solve the remaining test cases, or exit if all test cases have been solved.
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
2
6
0
1
9
1
Output
? 1 2 3
? 3 4 5
! 3 4 1 2
? 7 1 9
! 4 2 3 6 8
Note
Explanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):
For the first test case:
Question "? 1 2 3" returns 0, so there are more impostors than crewmates among players 1, 2 and 3.
Question "? 3 4 5" returns 1, so there are more crewmates than impostors among players 3, 4 and 5.
Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are k = 3 impostors. The players who are impostors are players 4, 1 and 2.
For the second test case:
Question "? 7 1 9" returns 1, so there are more crewmates than impostors among players 7, 1 and 9.
Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are k = 4 impostors. The players who are impostors are players 2, 3, 6 and 8. | #include <bits/stdc++.h>
using namespace std;
int ask(int a, int b, int c) {
cout << "? " << a + 1 << " " << b + 1 << " " << c + 1 << endl;
int r;
cin >> r;
return r;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int q[n];
fill(q, q + n, -1);
int one = -1, zero = -1;
for (int i = 1; i < n;) {
q[i] = ask(i - 1, i, i + 1);
i += 3;
}
for (int i = 1; i < n - 2; i += 3) {
if (q[i] != q[i + 3]) {
if (q[i] == 0) {
zero = i, one = i + 3;
} else {
zero = i + 3, one = i;
}
}
}
int crew = -1, imp = -1;
for (int i = min(zero, one); i <= max(zero, one); ++i) {
if (q[i] == -1) q[i] = ask(i - 1, i, i + 1);
}
for (int i = min(zero, one); i < max(zero, one); ++i) {
if (q[i] != q[i + 1]) {
if (q[i] == 0) {
crew = i + 2, imp = i - 1;
} else {
crew = i - 1, imp = i + 2;
}
}
}
int tp[n];
memset(tp, -1, n);
tp[crew] = 0, tp[imp] = 1;
for (int i = 1; i < n;) {
if (q[i] == 0) {
if (abs(i - crew) <= 1 && abs(i - imp) <= 1) {
int v = i - 1 + i + i + 1 - crew - imp;
tp[crew] = 1, tp[imp] = 0, tp[v] = ask(crew, imp, v);
} else if (abs(i - crew) <= 1) {
tp[i - 1] = tp[i] = tp[i + 1] = 0;
tp[crew] = 1;
} else if (abs(i - imp) <= 1) {
if (imp == i - 1) {
tp[i - 1] = 0, tp[i] = ask(imp, crew, i),
tp[i + 1] = ask(imp, crew, i + 1);
} else if (imp == i) {
tp[i - 1] = ask(imp, crew, i - 1), tp[i] = 0,
tp[i + 1] = ask(imp, crew, i + 1);
} else {
tp[i - 1] = ask(imp, crew, i - 1), tp[i] = ask(imp, crew, i),
tp[i + 1] = 0;
}
} else {
int p1 = ask(i - 1, i, crew), p2 = ask(i, i + 1, crew);
if (p1 == 1 && p2 == 1) {
tp[i - 1] = 0, tp[i] = 1, tp[i + 1] = 0;
} else if (p1 == 1) {
tp[i - 1] = 1, tp[i] = 0, tp[i + 1] = 0;
} else if (p2 == 1) {
tp[i - 1] = 0, tp[i] = 0, tp[i + 1] = 1;
} else {
tp[i - 1] = tp[i] = tp[i + 1] = 0;
}
}
} else {
if (abs(i - crew) <= 1 && abs(i - imp) <= 1) {
int v = i - 1 + i + i + 1 - crew - imp;
tp[crew] = 1, tp[imp] = 0, tp[v] = ask(crew, imp, v);
} else if (abs(i - crew) <= 1) {
if (crew == i - 1) {
tp[i - 1] = 1, tp[i] = ask(imp, crew, i),
tp[i + 1] = ask(imp, crew, i + 1);
} else if (crew == i) {
tp[i - 1] = ask(imp, crew, i - 1), tp[i] = 1,
tp[i + 1] = ask(imp, crew, i + 1);
} else {
tp[i - 1] = ask(imp, crew, i - 1), tp[i] = ask(imp, crew, i),
tp[i + 1] = 1;
}
} else if (abs(i - imp) <= 1) {
tp[i - 1] = tp[i] = tp[i + 1] = 1;
tp[imp] = 0;
} else {
int p1 = ask(i - 1, i, imp), p2 = ask(i, i + 1, imp);
if (p1 == 0 && p2 == 0) {
tp[i - 1] = 1, tp[i] = 0, tp[i + 1] = 1;
} else if (p1 == 0) {
tp[i - 1] = 0, tp[i] = 1, tp[i + 1] = 1;
} else if (p2 == 0) {
tp[i - 1] = 1, tp[i] = 1, tp[i + 1] = 0;
} else {
tp[i - 1] = tp[i] = tp[i + 1] = 1;
}
}
}
i += 3;
}
vector<int> ans;
for (int i = 0; i < n; ++i) {
if (tp[i] == 0) ans.push_back(i);
}
cout << "! " << ans.size() << " ";
for (auto u : ans) {
cout << u + 1 << " ";
}
cout << endl;
}
}
|
Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains n chocolates. The i-th chocolate has a non-negative integer type a_i.
Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all a_i are distinct). Icy wants to make at least one pair of chocolates the same type.
As a result, she asks her grandparents to perform some chocolate exchanges. Before performing any chocolate exchanges, Icy chooses two chocolates with indices x and y (1 ≤ x, y ≤ n, x ≠ y).
In a chocolate exchange, Icy's grandparents choose a non-negative integer k, such that 2^k ≥ a_x, and change the type of the chocolate x from a_x to 2^k - a_x (that is, perform a_x := 2^k - a_x).
The chocolate exchanges will be stopped only when a_x = a_y. Note that other pairs of equal chocolate types do not stop the procedure.
Icy's grandparents are smart, so they would choose the sequence of chocolate exchanges that minimizes the number of exchanges needed. Since Icy likes causing trouble, she wants to maximize the minimum number of exchanges needed by choosing x and y appropriately. She wonders what is the optimal pair (x, y) such that the minimum number of exchanges needed is maximized across all possible choices of (x, y).
Since Icy is not good at math, she hopes that you can help her solve the problem.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of chocolates.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9).
It is guaranteed that all a_i are distinct.
Output
Output three integers x, y, and m.
x and y are indices of the optimal chocolates to perform exchanges on. Your output must satisfy 1 ≤ x, y ≤ n, x ≠ y.
m is the number of exchanges needed to obtain a_x = a_y. We can show that m ≤ 10^9 for any pair of chocolates.
If there are multiple solutions, output any.
Examples
Input
5
5 6 7 8 9
Output
2 5 5
Input
2
4 8
Output
1 2 2
Note
In the first test case, the minimum number of exchanges needed to exchange a chocolate of type 6 to a chocolate of type 9 is 5. The sequence of exchanges is as follows: 6 → 2 → 0 → 1 → 7 → 9.
In the second test case, the minimum number of exchanges needed to exchange a chocolate of type 4 to a chocolate of type 8 is 2. The sequence of exchanges is as follows: 4 → 0 → 8. | #include <bits/stdc++.h>
const double PI = 3.1415926535897932384626433;
using namespace std;
struct edge {
long long to, cost;
edge() {}
edge(long long a, long long b) { to = a, cost = b; }
};
const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int mod = 1000000007;
struct mint {
int x;
mint(long long y = 0) {
if (y < 0 || y >= mod) y = (y % mod + mod) % mod;
x = y;
}
mint(const mint &ope) { x = ope.x; }
mint operator-() { return mint(-x); }
mint operator+(const mint &ope) { return mint(x) += ope; }
mint operator-(const mint &ope) { return mint(x) -= ope; }
mint operator*(const mint &ope) { return mint(x) *= ope; }
mint operator/(const mint &ope) { return mint(x) /= ope; }
mint &operator+=(const mint &ope) {
x += ope.x;
if (x >= mod) x -= mod;
return *this;
}
mint &operator-=(const mint &ope) {
x += mod - ope.x;
if (x >= mod) x -= mod;
return *this;
}
mint &operator*=(const mint &ope) {
long long tmp = x;
tmp *= ope.x, tmp %= mod;
x = tmp;
return *this;
}
mint &operator/=(const mint &ope) {
long long n = mod - 2;
mint mul = ope;
while (n) {
if (n & 1) *this *= mul;
mul *= mul;
n >>= 1;
}
return *this;
}
mint inverse() { return mint(1) / *this; }
bool operator==(const mint &ope) { return x == ope.x; }
bool operator!=(const mint &ope) { return x != ope.x; }
bool operator<(const mint &ope) const { return x < ope.x; }
};
mint modpow(mint a, long long n) {
if (n == 0) return mint(1);
if (n % 2)
return a * modpow(a, n - 1);
else
return modpow(a * a, n / 2);
}
istream &operator>>(istream &is, mint &ope) {
long long t;
is >> t, ope.x = t;
return is;
}
ostream &operator<<(ostream &os, mint &ope) { return os << ope.x; }
ostream &operator<<(ostream &os, const mint &ope) { return os << ope.x; }
long long modpow(long long a, long long n, long long mod) {
if (n == 0) return 1;
if (n % 2)
return ((a % mod) * (modpow(a, n - 1, mod) % mod)) % mod;
else
return modpow((a * a) % mod, n / 2, mod) % mod;
}
vector<mint> fact, fact_inv;
void make_fact(int n) {
fact.resize(n + 1), fact_inv.resize(n + 1);
fact[0] = mint(1);
for (long long i = (1); (i) <= (n); (i)++) fact[i] = fact[i - 1] * mint(i);
fact_inv[n] = fact[n].inverse();
for (long long i = (n - 1); (i) >= (0); (i)--)
fact_inv[i] = fact_inv[i + 1] * mint(i + 1);
}
mint comb(int n, int k) {
if (n < 0 || k < 0 || n < k) return mint(0);
return fact[n] * fact_inv[k] * fact_inv[n - k];
}
mint perm(int n, int k) { return comb(n, k) * fact[k]; }
vector<int> prime, pvec, qrime;
void make_prime(int n) {
prime.resize(n + 1);
for (long long i = (2); (i) <= (n); (i)++) {
if (prime[i] == 0) pvec.push_back(i), prime[i] = i;
for (auto p : pvec) {
if (i * p > n || p > prime[i]) break;
prime[i * p] = p;
}
}
}
void make_qrime(int n) {
qrime.resize(n + 1);
for (long long i = (2); (i) <= (n); (i)++) {
int ni = i / prime[i];
if (prime[i] == prime[ni])
qrime[i] = qrime[ni] * prime[i];
else
qrime[i] = prime[i];
}
}
bool exceed(long long x, long long y, long long m) { return x >= m / y + 1; }
void mark() { cout << "*" << endl; }
void yes() { cout << "YES" << endl; }
void no() { cout << "NO" << endl; }
long long floor(long long a, long long b) {
if (b < 0) a *= -1, b *= -1;
if (a >= 0)
return a / b;
else
return -((-a + b - 1) / b);
}
long long ceil(long long a, long long b) {
if (b < 0) a *= -1, b *= -1;
if (a >= 0)
return (a + b - 1) / b;
else
return -((-a) / b);
}
long long modulo(long long a, long long b) {
b = abs(b);
return a - floor(a, b) * b;
}
long long sgn(long long x) {
if (x > 0) return 1;
if (x < 0) return -1;
return 0;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
long long arith(long long x) { return x * (x + 1) / 2; }
long long arith(long long l, long long r) { return arith(r) - arith(l - 1); }
long long digitnum(long long x, long long b = 10) {
long long ret = 0;
for (; x; x /= b) ret++;
return ret;
}
long long digitsum(long long x, long long b = 10) {
long long ret = 0;
for (; x; x /= b) ret += x % b;
return ret;
}
string lltos(long long x) {
string ret;
for (; x; x /= 10) ret += x % 10 + '0';
reverse((ret).begin(), (ret).end());
return ret;
}
long long stoll(string &s) {
long long ret = 0;
for (auto c : s) ret *= 10, ret += c - '0';
return ret;
}
template <typename T>
void uniq(T &vec) {
sort((vec).begin(), (vec).end());
vec.erase(unique((vec).begin(), (vec).end()), vec.end());
}
int popcount(unsigned long long x) {
x -= ((x >> 1) & 0x5555555555555555ULL),
x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
return (((x + (x >> 4)) & 0x0F0F0F0F0F0F0F0FULL) * 0x0101010101010101ULL) >>
56;
}
template <class S, class T>
pair<S, T> &operator+=(pair<S, T> &s, const pair<S, T> &t) {
s.first += t.first, s.second += t.second;
return s;
}
template <class S, class T>
pair<S, T> &operator-=(pair<S, T> &s, const pair<S, T> &t) {
s.first -= t.first, s.second -= t.second;
return s;
}
template <class S, class T>
pair<S, T> operator+(const pair<S, T> &s, const pair<S, T> &t) {
return pair<S, T>(s.first + t.first, s.second + t.second);
}
template <class S, class T>
pair<S, T> operator-(const pair<S, T> &s, const pair<S, T> &t) {
return pair<S, T>(s.first - t.first, s.second - t.second);
}
template <class T>
T dot(const pair<T, T> &s, const pair<T, T> &t) {
return s.first * t.first + s.second * t.second;
}
template <class T>
T cross(const pair<T, T> &s, const pair<T, T> &t) {
return s.first * t.second - s.second * t.first;
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> &vec) {
for (long long i = 0; (i) < (long long)(vec).size(); (i)++)
os << vec[i] << " ";
return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &vec) {
for (long long i = 0; (i) < (long long)(vec).size(); (i)++)
os << vec[i] << " ";
return os;
}
template <typename T>
ostream &operator<<(ostream &os, deque<T> &deq) {
for (long long i = 0; (i) < (long long)(deq).size(); (i)++)
os << deq[i] << " ";
return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, pair<T, U> &ope) {
os << "(" << ope.first << ", " << ope.second << ")";
return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &ope) {
os << "(" << ope.first << ", " << ope.second << ")";
return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, map<T, U> &ope) {
for (auto p : ope) os << "(" << p.first << ", " << p.second << "),";
return os;
}
template <typename T>
ostream &operator<<(ostream &os, set<T> &ope) {
for (auto x : ope) os << x << " ";
return os;
}
template <typename T>
ostream &operator<<(ostream &os, multiset<T> &ope) {
for (auto x : ope) os << x << " ";
return os;
}
template <typename T>
void outa(T a[], long long s, long long t) {
for (long long i = (s); (i) <= (t); (i)++) {
cout << a[i];
if (i < t) cout << " ";
}
cout << endl;
}
void dump_func() { cout << endl; }
template <class Head, class... Tail>
void dump_func(Head &&head, Tail &&...tail) {
cout << head;
if (sizeof...(Tail) > 0) cout << " ";
dump_func(std::move(tail)...);
}
struct Trie {
struct TrieNode {
int num, next[2];
TrieNode() {
num = 0;
for (int i = 0; i < 2; i++) next[i] = -1;
}
};
vector<TrieNode> vec;
Trie() { init(); }
void init() {
vec.clear();
vec.push_back(TrieNode());
}
int seek(string &s) {
int p = 0;
for (int i = 0; i < s.size(); i++) {
int c = s[i] - '0';
if (vec[p].next[c] == -1) {
vec.push_back(TrieNode());
vec[p].next[c] = (int)vec.size() - 1;
}
p = vec[p].next[c];
}
return p;
}
void insert(string &s, int x = 1) {
int p = seek(s);
vec[p].num = x;
}
void erase(string &s, int x = 1) {
int p = seek(s);
vec[p].num = max(0, vec[p].num - x);
}
int count(string &s) {
int p = seek(s);
return vec[p].num;
}
};
long long n;
long long a[200005];
Trie trie;
pair<long long, pair<long long, long long> > ans;
pair<long long, long long> dfs(int v) {
pair<long long, long long> ret =
pair<long long, long long>(0, trie.vec[v].num),
res0, res1;
if (trie.vec[v].next[0] != -1) res0 = dfs(trie.vec[v].next[0]);
if (trie.vec[v].next[1] != -1)
res1 = dfs(trie.vec[v].next[1]) + pair<long long, long long>(1, 0);
(ret) = max((ret), (res0)), (ret) = max((ret), (res1));
if (trie.vec[v].next[0] != -1 && trie.vec[v].next[1] != -1) {
(ans) =
max((ans),
(make_pair(res0.first + res1.first,
pair<long long, long long>(res0.second, res1.second))));
}
return ret;
}
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (long long i = (1); (i) <= (n); (i)++) {
cin >> a[i];
string s;
for (long long j = (0); (j) <= (32); (j)++) {
s += a[i] % 2 + '0';
a[i] /= 2;
}
string t;
bool flag = false;
for (long long j = (0); (j) <= (31); (j)++) {
if (!flag && s[j] == '1') {
flag = true;
t += "1";
continue;
}
if (flag && s[j] != s[j + 1])
t += "1";
else
t += "0";
}
trie.insert(t, i);
}
ans = make_pair(0, pair<long long, long long>(2e18, 2e18));
dfs(0);
if (ans.first == 0) ans = make_pair(0, pair<long long, long long>(1, 2));
dump_func(ans.second.first, ans.second.second, ans.first);
return 0;
}
|
Polycarp had an array a of 3 positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array b of 7 integers.
For example, if a = \{1, 4, 3\}, then Polycarp wrote out 1, 4, 3, 1 + 4 = 5, 1 + 3 = 4, 4 + 3 = 7, 1 + 4 + 3 = 8. After sorting, he got an array b = \{1, 3, 4, 4, 5, 7, 8\}.
Unfortunately, Polycarp lost the array a. He only has the array b left. Help him to restore the array a.
Input
The first line contains one integer t (1 ≤ t ≤ 5000) — the number of test cases.
Each test case consists of one line which contains 7 integers b_1, b_2, ..., b_7 (1 ≤ b_i ≤ 10^9; b_i ≤ b_{i+1}).
Additional constraint on the input: there exists at least one array a which yields this array b as described in the statement.
Output
For each test case, print 3 integers — a_1, a_2 and a_3. If there can be several answers, print any of them.
Example
Input
5
1 3 4 4 5 7 8
1 2 3 4 5 6 7
300000000 300000000 300000000 600000000 600000000 600000000 900000000
1 1 2 999999998 999999999 999999999 1000000000
1 2 2 3 3 4 5
Output
1 4 3
4 1 2
300000000 300000000 300000000
999999998 1 1
1 2 2
Note
The subsequence of the array a is a sequence that can be obtained from a by removing zero or more of its elements.
Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length 3 has exactly 7 different non-empty subsequences. | t = int(input())
for i in range(t):
k=[]
z=[]
a = list(map(int, input().split()[:7]))
a.sort()
k = a[-1]-(a[0]+a[1])
z = [str(a[0]), str(a[1])]
a.pop(0)
a.pop(0)
for i in a:
if i==k:
z.append(str(i))
break
print(" ".join(z)) |
Polycarp has come up with a new game to play with you. He calls it "A missing bigram".
A bigram of a word is a sequence of two adjacent letters in it.
For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".
The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard in the same order as they appear in the word. After that, he wipes one of them off the whiteboard.
Finally, Polycarp invites you to guess what the word that he has come up with was.
Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.
The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of testcases.
The first line of each testcase contains a single integer n (3 ≤ n ≤ 100) — the length of the word Polycarp has come up with.
The second line of each testcase contains n-2 bigrams of that word, separated by a single space. Each bigram consists of two letters, each of them is either 'a' or 'b'.
Additional constraint on the input: there exists at least one string such that it is possible to write down all its bigrams, except one, so that the resulting sequence is the same as the sequence in the input. In other words, the answer exists.
Output
For each testcase print a word, consisting of n letters, each of them should be either 'a' or 'b'. It should be possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.
The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.
Example
Input
4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb
Output
abbaaba
abaabaa
baa
bbabb
Note
The first two testcases from the example are produced from the word "abbaaba". As listed in the statement, it contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".
In the first testcase, the 5-th bigram is removed.
In the second testcase, the 2-nd bigram is removed. However, that sequence could also have been produced from the word "abaabaa". It contains bigrams "ab", "ba", "aa", "ab", "ba" and "aa". The missing bigram is the 6-th one.
In the third testcase, all of "baa", "aab" and "aaa" are valid answers. | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
long long int ar[N], br[N], l[N], r[N];
int parent[1000];
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<string> v;
n = n - 2;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
v.push_back(s);
}
if (n == 1) {
cout << "a" << v[0] << endl;
continue;
}
cout << v[0][0];
int flag = 0;
for (int i = 0; i < v.size() - 1; i++) {
if (v[i][1] == v[i + 1][0])
cout << v[i + 1][0];
else {
flag = 1;
cout << v[i][1];
cout << v[i + 1][0];
}
}
cout << v[n - 1][1];
if (flag == 0) cout << "a";
cout << endl;
}
return 0;
}
|
You are given an array a consisting of n positive integers. You have to choose a positive integer d and paint all elements into two colors. All elements which are divisible by d will be painted red, and all other elements will be painted blue.
The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of d which yields a beautiful coloring, or report that it is impossible.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
The first line of each testcase contains one integer n (2 ≤ n ≤ 100) — the number of elements of the array.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
Output
For each testcase print a single integer. If there is no such value of d that yields a beautiful coloring, print 0. Otherwise, print any suitable value of d (1 ≤ d ≤ 10^{18}).
Example
Input
5
5
1 2 3 4 5
3
10 5 15
3
100 10 200
10
9 8 2 6 6 2 8 6 5 4
2
1 3
Output
2
0
100
0
3 | from collections import Counter, defaultdict
import math
import bisect
def getlist():
return list(map(int, input().split()))
def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
def maplist():
return map(int, input().split())
def main():
t = int(input())
for num in range(t):
n = int(input())
arr = getlist()
gcd1 = arr[0]
gcd2 = arr[1]
for i,numbers in enumerate(arr):
if i%2==0:
gcd1 = compute_gcd(gcd1,numbers)
else:
gcd2 = compute_gcd(gcd2,numbers)
# print(gcd1,gcd2)
i = 1
flag= True
while i<n and gcd1>1:
if arr[i]%gcd1==0:
flag = False
break
i+=2
if flag is True and gcd1>1:
print(gcd1)
else:
i = 0
flag1 = True
while i<n and gcd2>1:
if arr[i]%gcd2==0:
flag1 = False
break
i+=2
if flag1 is True and gcd2>1:
print(gcd2)
else:
print(0)
main()
|
You are given an array a of n integers, and another integer k such that 2k ≤ n.
You have to perform exactly k operations with this array. In one operation, you have to choose two elements of the array (let them be a_i and a_j; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add ⌊ (a_i)/(a_j) ⌋ to your score, where ⌊ x/y ⌋ is the maximum integer not exceeding x/y.
Initially, your score is 0. After you perform exactly k operations, you add all the remaining elements of the array to the score.
Calculate the minimum possible score you can get.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 500) — the number of test cases.
Each test case consists of two lines. The first line contains two integers n and k (1 ≤ n ≤ 100; 0 ≤ k ≤ ⌊ n/2 ⌋).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5).
Output
Print one integer — the minimum possible score you can get.
Example
Input
5
7 3
1 1 1 2 1 3 1
5 1
5 5 5 5 5
4 2
1 3 3 7
2 0
4 2
9 2
1 10 10 1 10 2 7 10 3
Output
2
16
0
6
16
Note
Let's consider the example test.
In the first test case, one way to obtain a score of 2 is the following one:
1. choose a_7 = 1 and a_4 = 2 for the operation; the score becomes 0 + ⌊ 1/2 ⌋ = 0, the array becomes [1, 1, 1, 1, 3];
2. choose a_1 = 1 and a_5 = 3 for the operation; the score becomes 0 + ⌊ 1/3 ⌋ = 0, the array becomes [1, 1, 1];
3. choose a_1 = 1 and a_2 = 1 for the operation; the score becomes 0 + ⌊ 1/1 ⌋ = 1, the array becomes [1];
4. add the remaining element 1 to the score, so the resulting score is 2.
In the second test case, no matter which operations you choose, the resulting score is 16.
In the third test case, one way to obtain a score of 0 is the following one:
1. choose a_1 = 1 and a_2 = 3 for the operation; the score becomes 0 + ⌊ 1/3 ⌋ = 0, the array becomes [3, 7];
2. choose a_1 = 3 and a_2 = 7 for the operation; the score becomes 0 + ⌊ 3/7 ⌋ = 0, the array becomes empty;
3. the array is empty, so the score doesn't change anymore.
In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: 4 + 2 = 6. | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> ar(n);
for (int i = 0; i < n; i++) {
cin >> ar[i];
}
sort(ar.begin(), ar.end());
long long int ans = 0;
for (int i = 0; i < n - k; i++) {
if (i < n - 2 * k)
ans += ar[i];
else
ans += (ar[i] / ar[i + k]);
}
cout << ans << endl;
}
return 0;
}
|
n towns are arranged in a circle sequentially. The towns are numbered from 1 to n in clockwise order. In the i-th town, there lives a singer with a repertoire of a_i minutes for each i ∈ [1, n].
Each singer visited all n towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the i-th singer got inspired and came up with a song that lasts a_i minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.
Hence, for the i-th singer, the concert in the i-th town will last a_i minutes, in the (i + 1)-th town the concert will last 2 ⋅ a_i minutes, ..., in the ((i + k) mod n + 1)-th town the duration of the concert will be (k + 2) ⋅ a_i, ..., in the town ((i + n - 2) mod n + 1) — n ⋅ a_i minutes.
You are given an array of b integer numbers, where b_i is the total duration of concerts in the i-th town. Reconstruct any correct sequence of positive integers a or say that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10^3) — the number of test cases. Then the test cases follow.
Each test case consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 4 ⋅ 10^4) — the number of cities. The second line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}) — the total duration of concerts in i-th city.
The sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If there is no suitable sequence a, print NO. Otherwise, on the first line print YES, on the next line print the sequence a_1, a_2, ..., a_n of n integers, where a_i (1 ≤ a_i ≤ 10^{9}) is the initial duration of repertoire of the i-th singer. If there are multiple answers, print any of them.
Example
Input
4
3
12 16 14
1
1
3
1 2 3
6
81 75 75 93 93 87
Output
YES
3 1 3
YES
1
NO
YES
5 5 4 1 4 5
Note
Let's consider the 1-st test case of the example:
1. the 1-st singer in the 1-st city will give a concert for 3 minutes, in the 2-nd — for 6 minutes, in the 3-rd — for 9 minutes;
2. the 2-nd singer in the 1-st city will give a concert for 3 minutes, in the 2-nd — for 1 minute, in the 3-rd - for 2 minutes;
3. the 3-rd singer in the 1-st city will give a concert for 6 minutes, in the 2-nd — for 9 minutes, in the 3-rd — for 3 minutes. | T = int(input())
for _ in range(T):
n = int(input())
B = [int(i) for i in input().split()]
m = n*(n+1)//2
if sum(B) % m != 0:
print("NO")
else:
A = sum(B)//m
ans = []
for i, j in zip(B, B[1:] + [B[0]]):
ans += [(A + i - j)/n]
if any(int(x) != x or x <= 0 for x in ans):
print("NO")
else:
print("YES")
print(" ".join(str(int(x)) for x in [ans[-1]] + ans[:-1]))
|
You are given two positive integers x and y. You can perform the following operation with x: write it in its binary form without leading zeros, add 0 or 1 to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of x.
For example:
* 34 can be turned into 81 via one operation: the binary form of 34 is 100010, if you add 1, reverse it and remove leading zeros, you will get 1010001, which is the binary form of 81.
* 34 can be turned into 17 via one operation: the binary form of 34 is 100010, if you add 0, reverse it and remove leading zeros, you will get 10001, which is the binary form of 17.
* 81 can be turned into 69 via one operation: the binary form of 81 is 1010001, if you add 0, reverse it and remove leading zeros, you will get 1000101, which is the binary form of 69.
* 34 can be turned into 69 via two operations: first you turn 34 into 81 and then 81 into 69.
Your task is to find out whether x can be turned into y after a certain number of operations (possibly zero).
Input
The only line of the input contains two integers x and y (1 ≤ x, y ≤ 10^{18}).
Output
Print YES if you can make x equal to y and NO if you can't.
Examples
Input
3 3
Output
YES
Input
7 4
Output
NO
Input
2 8
Output
NO
Input
34 69
Output
YES
Input
8935891487501725 71487131900013807
Output
YES
Note
In the first example, you don't even need to do anything.
The fourth example is described in the statement. | #import io,os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
def main(t):
x, y = map(int,input().split())
sx, sy = bin(x)[2:],bin(y)[2:]
dic = {}
queue = deque()
queue.append(sx)
dic[sx] = 1
i = len(sx)-1
while i>=0 and sx[i]=='0': i -= 1
queue.append(sx[:i+1])
dic[sx[:i+1]] = 1
# print(dic)
while queue:
curr = queue.popleft()
nextcurr1 = curr[::-1]
i = 0
while nextcurr1[i]=='0': i += 1
nextcurr1 = nextcurr1[i:]
if nextcurr1 not in dic:
dic[nextcurr1] = 1
queue.append(nextcurr1)
nextcurr2 = (curr + '1')[::-1]
if nextcurr2 not in dic:
dic[nextcurr2] = 1
if len(nextcurr2) <= len(sy): queue.append(nextcurr2)
# print(dic)
if sy in dic:
print("YES")
else:
print("NO")
T = 1 #int(input())
t = 1
while t<=T:
main(t)
t += 1
|
Monocarp plays a computer game (yet again!). This game has a unique trading mechanics.
To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price x, then he can trade it for any item (exactly one item) with price not greater than x+k.
Monocarp initially has n items, the price of the i-th item he has is a_i. The character Monocarp is trading with has m items, the price of the i-th item they have is b_i. Monocarp can trade with this character as many times as he wants (possibly even zero times), each time exchanging one of his items with one of the other character's items according to the aforementioned constraints. Note that if Monocarp gets some item during an exchange, he can trade it for another item (since now the item belongs to him), and vice versa: if Monocarp trades one of his items for another item, he can get his item back by trading something for it.
You have to answer q queries. Each query consists of one integer, which is the value of k, and asks you to calculate the maximum possible total cost of items Monocarp can have after some sequence of trades, assuming that he can trade an item of cost x for an item of cost not greater than x+k during each trade. Note that the queries are independent: the trades do not actually occur, Monocarp only wants to calculate the maximum total cost he can get.
Input
The first line contains three integers n, m and q (1 ≤ n, m, q ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the prices of the items Monocarp has.
The third line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ 10^9) — the prices of the items the other character has.
The fourth line contains q integers, where the i-th integer is the value of k for the i-th query (0 ≤ k ≤ 10^9).
Output
For each query, print one integer — the maximum possible total cost of items Monocarp can have after some sequence of trades, given the value of k from the query.
Example
Input
3 4 5
10 30 15
12 31 14 18
0 1 2 3 4
Output
55
56
60
64
64 | from itertools import accumulate
class Dsu:
def __init__(self, n):
self.f = list(range(n))
def find(self, x):
if self.f[x] != x:
self.f[x] = self.find(self.f[x])
return self.f[x]
def union(self, i, j, cnt, psum, maxv):
fi, fj = self.find(i), self.find(j)
if fi != fj:
if fi < fj:
fi, fj = fj, fi
self.f[fj] = fi
l1, l2 = cnt[fi], cnt[fj]
l3 = l1 + l2
cnt[fi] = l3
maxv += psum[fi + 1 - l1] - psum[fi + 1 - l3] - (psum[fj + 1] - psum[fj + 1 - l2])
return maxv
def main():
n, m, q = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
qs = list(map(int, input().split()))
qss = list(zip(qs, list(range(q))))
qss.sort()
nums = a + b
nums.sort()
tot = len(nums)
cnt = [0] * tot
i = j = 0
a.sort()
while i < n:
while a[i] != nums[j]:
j += 1
cnt[j] = 1
i += 1
j += 1
edges = []
for i in range(tot):
if i + 1 < tot:
edges.append([nums[i + 1] - nums[i], i, i + 1])
edges.sort(reverse=True)
dsu = Dsu(tot)
psum = [0] + list(accumulate(nums))
maxv = sum(a)
ans = [0] * q
for k, idx in qss:
while edges and edges[-1][0] <= k:
_, i, j = edges.pop()
maxv = dsu.union(i, j, cnt, psum, maxv)
ans[idx] = maxv
print(*ans, sep=" ")
return
if __name__ == "__main__":
main()
|
A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.
For a given string s determine if it is square.
Input
The first line of input data contains an integer t (1 ≤ t ≤ 100) —the number of test cases.
This is followed by t lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between 1 and 100 inclusive.
Output
For each test case, output on a separate line:
* YES if the string in the corresponding test case is square,
* NO otherwise.
You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
Example
Input
10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy
Output
NO
YES
NO
YES
YES
YES
NO
NO
NO
YES | #include <bits/stdc++.h>
using namespace std;
int main() {
int t, s, d;
cin >> t;
while (t--) {
int count = 0;
string a;
cin >> a;
s = a.size();
d = s / 2;
if (s % 2 == 1) {
cout << "no" << endl;
} else {
for (int i = 0; i < d; i++) {
if (a[i] != a[i + d]) {
count = 1;
break;
}
}
if (count == 1)
cout << "no" << endl;
else
cout << "yes" << endl;
}
}
}
|
Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: 1, 4, 8, 9, ....
For a given number n, count the number of integers from 1 to n that Polycarp likes. In other words, find the number of such x that x is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).
Input
The first line contains an integer t (1 ≤ t ≤ 20) — the number of test cases.
Then t lines contain the test cases, one per line. Each of the lines contains one integer n (1 ≤ n ≤ 10^9).
Output
For each test case, print the answer you are looking for — the number of integers from 1 to n that Polycarp likes.
Example
Input
6
10
1
25
1000000000
999999999
500000000
Output
4
1
6
32591
32590
23125 | import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
long n=sc.nextLong();
long ans=(long)Math.sqrt(n)+(long)Math.cbrt(n)-(long)Math.sqrt(Math.cbrt(n));
System.out.println(ans);
}
}
}
|
Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers a and b using the following algorithm:
1. If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.
2. The numbers are processed from right to left (that is, from the least significant digits to the most significant).
3. In the first step, she adds the last digit of a to the last digit of b and writes their sum in the answer.
4. At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer.
For example, the numbers a = 17236 and b = 3465 Tanya adds up as follows:
$$$ \large{ \begin{array}{r} + \begin{array}{r} 17236\\\ 03465\\\ \end{array} \\\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} $$$
* calculates the sum of 6 + 5 = 11 and writes 11 in the answer.
* calculates the sum of 3 + 6 = 9 and writes the result to the left side of the answer to get 911.
* calculates the sum of 2 + 4 = 6 and writes the result to the left side of the answer to get 6911.
* calculates the sum of 7 + 3 = 10, and writes the result to the left side of the answer to get 106911.
* calculates the sum of 1 + 0 = 1 and writes the result to the left side of the answer and get 1106911.
As a result, she gets 1106911.
You are given two positive integers a and s. Find the number b such that by adding a and b as described above, Tanya will get s. Or determine that no suitable b exists.
Input
The first line of input data contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Each test case consists of a single line containing two positive integers a and s (1 ≤ a < s ≤ 10^{18}) separated by a space.
Output
For each test case print the answer on a separate line.
If the solution exists, print a single positive integer b. The answer must be written without leading zeros. If multiple answers exist, print any of them.
If no suitable number b exists, output -1.
Example
Input
6
17236 1106911
1 5
108 112
12345 1023412
1 11
1 20
Output
3465
4
-1
90007
10
-1
Note
The first test case is explained in the main part of the statement.
In the third test case, we cannot choose b that satisfies the problem statement. | #include <bits/stdc++.h>
using namespace std;
string solve() {
string a, s, b = "";
cin >> a >> s;
reverse(a.begin(), a.end());
reverse(s.begin(), s.end());
int k = 0;
for (int i = 0; i < a.size(); i++) {
if (i + k >= s.size()) {
return "-1";
}
if (a[i] == s[i + k]) {
b = "0" + b;
}
if (a[i] < s[i + k]) {
char h = s[i + k] - a[i] + 48;
b = h + b;
}
if (a[i] > s[i + k]) {
if (i + k == s.size() - 1) return "-1";
string b1 = s.substr(i + k, 2);
reverse(b1.begin(), b1.end());
int h = stoi(b1) - (a[i] - 48);
if (h >= 10 || h < 0) return "-1";
b = to_string(h) + b;
k++;
}
}
if (a.size() + k < s.size()) {
string h = s.substr(a.size() + k, s.size() - a.size() - k);
reverse(h.begin(), h.end());
b = h + b;
}
while (b[0] == '0' && b.size() > 1) {
b.erase(0, 1);
}
return b;
}
int main() {
int t;
cin >> t;
while (t > 0) {
cout << solve() << endl;
t--;
}
return 0;
}
|
Vlad has n friends, for each of whom he wants to buy one gift for the New Year.
There are m shops in the city, in each of which he can buy a gift for any of his friends. If the j-th friend (1 ≤ j ≤ n) receives a gift bought in the shop with the number i (1 ≤ i ≤ m), then the friend receives p_{ij} units of joy. The rectangular table p_{ij} is given in the input.
Vlad has time to visit at most n-1 shops (where n is the number of friends). He chooses which shops he will visit and for which friends he will buy gifts in each of them.
Let the j-th friend receive a_j units of joy from Vlad's gift. Let's find the value α=min\\{a_1, a_2, ..., a_n\}. Vlad's goal is to buy gifts so that the value of α is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends.
For example, let m = 2, n = 2. Let the joy from the gifts that we can buy in the first shop: p_{11} = 1, p_{12}=2, in the second shop: p_{21} = 3, p_{22}=4.
Then it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy 3, and for the second — bringing joy 4. In this case, the value α will be equal to min\{3, 4\} = 3
Help Vlad choose gifts for his friends so that the value of α is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most n-1 shops (where n is the number of friends). In the shop, he can buy any number of gifts.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input.
An empty line is written before each test case. Then there is a line containing integers m and n (2 ≤ n, 2 ≤ n ⋅ m ≤ 10^5) separated by a space — the number of shops and the number of friends, where n ⋅ m is the product of n and m.
Then m lines follow, each containing n numbers. The number in the i-th row of the j-th column p_{ij} (1 ≤ p_{ij} ≤ 10^9) is the joy of the product intended for friend number j in shop number i.
It is guaranteed that the sum of the values n ⋅ m over all test cases in the test does not exceed 10^5.
Output
Print t lines, each line must contain the answer to the corresponding test case — the maximum possible value of α, where α is the minimum of the joys from a gift for all of Vlad's friends.
Example
Input
5
2 2
1 2
3 4
4 3
1 3 1
3 1 1
1 2 2
1 1 3
2 3
5 3 4
2 5 1
4 2
7 9
8 1
9 6
10 8
2 4
6 5 2 1
7 9 7 2
Output
3
2
4
8
2 | #include <bits/stdc++.h>
using namespace std;
double PI = (acos(-1));
long long md = 1000000007;
long long pw(long long a, long long b) {
long long c = 1, m = a;
while (b) {
if (b & 1) c = (c * m);
m = (m * m);
b /= 2;
}
return c;
}
long long pwmd(long long a, long long b) {
long long c = 1, m = a;
while (b) {
if (b & 1) c = ((c * m)) % md;
m = (m * m) % md;
b /= 2;
}
return c;
}
long long modinv(long long n) { return pwmd(n, md - 2); }
long long nc2(long long n) { return (1ll * n * (n - 1)) / 2; }
bool prime(long long a) {
for (int i = 2; i * i <= a; i++) {
if (a % i == 0) return false;
}
return true;
}
long long ceel(long long a, long long b) {
if (a % b == 0)
return a / b;
else
return a / b + 1;
}
bool cch(long long a, long long b) {
long double x = a, y = b;
long double z = 1000000000000000000 / a;
if (y > z) return 0;
return 1;
}
void solve() {
long long m, n;
cin >> m >> n;
long long l[m][n];
for (long long i = 0; i < m; i++) {
for (long long j = 0; j < n; j++) cin >> l[i][j];
}
if (n - 1 >= m) {
vector<long long> ans;
for (long long i = 0; i < n; i++) {
long long mx = 0;
for (long long j = 0; j < m; j++) {
mx = max(mx, l[j][i]);
}
ans.push_back(mx);
}
sort(ans.begin(), ans.end());
cout << ans[0] << "\n";
return;
} else {
long long x = 1, y = 1000000001;
while (x + 1 < y) {
long long mid = (x + y) / 2, flg = 0, gg = 0;
map<long long, long long> mp;
for (long long i = 0; i < n; i++) {
long long zq = 0;
for (long long j = 0; j < m; j++) {
if (l[j][i] >= mid) {
zq = 1;
if (mp[j]) flg = 1;
mp[j] = 1;
}
}
if (zq == 0) gg = 1;
}
if (flg == 0 || gg) {
y = mid;
} else
x = mid;
}
cout << x << "\n";
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long tests = 1;
cin >> tests;
while (tests--) {
solve();
}
return 0;
}
|
Dmitry has an array of n non-negative integers a_1, a_2, ..., a_n.
In one operation, Dmitry can choose any index j (1 ≤ j ≤ n) and increase the value of the element a_j by 1. He can choose the same index j multiple times.
For each i from 0 to n, determine whether Dmitry can make the MEX of the array equal to exactly i. If it is possible, then determine the minimum number of operations to do it.
The MEX of the array is equal to the minimum non-negative integer that is not in the array. For example, the MEX of the array [3, 1, 0] is equal to 2, and the array [3, 3, 1, 4] is equal to 0.
Input
The first line of input data contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input.
The descriptions of the test cases follow.
The first line of the description of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a.
The second line of the description of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ n) — elements of the array a.
It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2⋅10^5.
Output
For each test case, output n + 1 integer — i-th number is equal to the minimum number of operations for which you can make the array MEX equal to i (0 ≤ i ≤ n), or -1 if this cannot be done.
Example
Input
5
3
0 1 3
7
0 1 2 3 4 3 2
4
3 0 0 0
7
4 6 2 3 5 0 5
5
4 0 1 0 4
Output
1 1 0 -1
1 1 2 2 1 0 2 6
3 0 1 4 3
1 0 -1 -1 -1 -1 -1 -1
2 1 0 2 -1 -1
Note
In the first set of example inputs, n=3:
* to get MEX=0, it is enough to perform one increment: a_1++;
* to get MEX=1, it is enough to perform one increment: a_2++;
* MEX=2 for a given array, so there is no need to perform increments;
* it is impossible to get MEX=3 by performing increments. | from typing import Counter
def find(arr: list, n):
res = [-1]*(n+1)
count = [0]*(n+1)
maxx = 0
maxxx = 0
d = 0
for i in range(n):
count[arr[i]] += 1
if count[0] < 1:
res[0] =0
return res
res[0] = count[0]
for i in range(1,n+1):
d = 0
res[i] = res[i-1] - count[i-1] + count[i]
if count[i-1] > 0:
if count[maxx] > 0:
maxxx = maxx
maxx = i-1
count[i-1] -= 1
else:
if count[maxx] >0:
d = i-1 - maxx
count[maxx] -= 1
else:
while maxxx > -1 and count[maxxx] < 1:
maxxx -= 1
if maxxx < 0:
res[i] = -1
return res
else:
d = i-1 - maxxx
count[maxxx] -= 1
res[i] += d
return res
r = int(input())
res = []
for i in range(r):
n = int(input())
arr = list(map(int, input().split()))
res.append(find(arr, n))
for i in res:
print(*i) |
The Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play).
n people gathered in a room with m tables (n ≥ 2m). They want to play the Hat k times. Thus, k games will be played at each table. Each player will play in k games.
To do this, they are distributed among the tables for each game. During each game, one player plays at exactly one table. A player can play at different tables.
Players want to have the most "fair" schedule of games. For this reason, they are looking for a schedule (table distribution for each game) such that:
* At any table in each game there are either ⌊n/m⌋ people or ⌈n/m⌉ people (that is, either n/m rounded down, or n/m rounded up). Different numbers of people can play different games at the same table.
* Let's calculate for each player the value b_i — the number of times the i-th player played at a table with ⌈n/m⌉ persons (n/m rounded up). Any two values of b_imust differ by no more than 1. In other words, for any two players i and j, it must be true |b_i - b_j| ≤ 1.
For example, if n=5, m=2 and k=2, then at the request of the first item either two players or three players should play at each table. Consider the following schedules:
* First game: 1, 2, 3 are played at the first table, and 4, 5 at the second one. The second game: at the first table they play 5, 1, and at the second — 2, 3, 4. This schedule is not "fair" since b_2=2 (the second player played twice at a big table) and b_5=0 (the fifth player did not play at a big table).
* First game: 1, 2, 3 are played at the first table, and 4, 5 at the second one. The second game: at the first table they play 4, 5, 2, and at the second one — 1, 3. This schedule is "fair": b=[1,2,1,1,1] (any two values of b_i differ by no more than 1).
Find any "fair" game schedule for n people if they play on the m tables of k games.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test.
Each test case consists of one line that contains three integers n, m and k (2 ≤ n ≤ 2⋅10^5, 1 ≤ m ≤ ⌊n/2⌋, 1 ≤ k ≤ 10^5) — the number of people, tables and games, respectively.
It is guaranteed that the sum of nk (n multiplied by k) over all test cases does not exceed 2⋅10^5.
Output
For each test case print a required schedule — a sequence of k blocks of m lines. Each block corresponds to one game, a line in a block corresponds to one table. In each line print the number of players at the table and the indices of the players (numbers from 1 to n) who should play at this table.
If there are several required schedules, then output any of them. We can show that a valid solution always exists.
You can output additional blank lines to separate responses to different sets of inputs.
Example
Input
3
5 2 2
8 3 1
2 1 3
Output
3 1 2 3
2 4 5
3 4 5 2
2 1 3
2 6 2
3 3 5 1
3 4 7 8
2 2 1
2 2 1
2 2 1 |
def solve():
n, m, k = readIntArr()
# assume n % m != 0
smallPeople = n // m # number of people at smallTable
largePeople = smallPeople + 1
smallTable = largePeople * m - n # number of small Tables
largeTable = m - smallTable
ans = []
largeIdx = 0
for roundd in range(k):
# put large tables
for _ in range(largeTable):
arr = [largePeople]
for __ in range(largePeople):
arr.append(largeIdx + 1)
largeIdx += 1
largeIdx %= n
ans.append(arr)
# put small tables
smallIdx = largeIdx
for _ in range(smallTable):
arr = [smallPeople]
for __ in range(smallPeople):
arr.append(smallIdx + 1)
smallIdx += 1
smallIdx %= n
ans.append(arr)
ans.append([''])
multiLineArrayOfArraysPrint(ans)
def main():
t = int(input())
for _ in range(t):
solve()
print()
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(ansArr):
print('! {}'.format(' '.join([str(x) for x in ansArr])))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() |
Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.
There are mines on the field, for each the coordinates of its location are known (x_i, y_i). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of k (two perpendicular lines). As a result, we get an explosion on the field in the form of a "plus" symbol ('+'). Thus, one explosion can cause new explosions, and so on.
Also, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode instantly and also instantly detonate other mines according to the rules described above.
Polycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test.
An empty line is written in front of each test suite.
Next comes a line that contains integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ k ≤ 10^9) — the number of mines and the distance that hit by mines during the explosion, respectively.
Then n lines follow, the i-th of which describes the x and y coordinates of the i-th mine and the time until its explosion (-10^9 ≤ x, y ≤ 10^9, 0 ≤ timer ≤ 10^9). It is guaranteed that all mines have different coordinates.
It is guaranteed that the sum of the values n over all test cases in the test does not exceed 2 ⋅ 10^5.
Output
Print t lines, each of the lines must contain the answer to the corresponding set of input data — the minimum number of seconds it takes to explode all the mines.
Example
Input
3
5 0
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
5 2
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
6 1
1 -1 3
0 -1 9
0 1 7
-1 0 1
-1 1 9
-1 -1 7
Output
2
1
0
Note
<image> Picture from examples
First example:
* 0 second: we explode a mine at the cell (2, 2), it does not detonate any other mine since k=0.
* 1 second: we explode the mine at the cell (0, 1), and the mine at the cell (0, 0) explodes itself.
* 2 second: we explode the mine at the cell (1, 1), and the mine at the cell (1, 0) explodes itself.
Second example:
* 0 second: we explode a mine at the cell (2, 2) we get:
<image>
* 1 second: the mine at coordinate (0, 0) explodes and since k=2 the explosion detonates mines at the cells (0, 1) and (1, 0), and their explosions detonate the mine at the cell (1, 1) and there are no mines left on the field. | #include <bits/stdc++.h>
using namespace std;
char BB[1 << 16], *SB = BB, *TB = BB;
template <typename T>
void read(T &n) {
T w = 1;
n = 0;
char ch =
(SB == TB && (TB = (SB = BB) + fread(BB, 1, 1 << 15, stdin), SB == TB)
? EOF
: *SB++);
while (!isdigit(ch)) {
if (ch == '-') w = -1;
ch = (SB == TB && (TB = (SB = BB) + fread(BB, 1, 1 << 15, stdin), SB == TB)
? EOF
: *SB++);
}
while (isdigit(ch)) {
n = (n << 3) + (n << 1) + (ch & 15);
ch = (SB == TB && (TB = (SB = BB) + fread(BB, 1, 1 << 15, stdin), SB == TB)
? EOF
: *SB++);
}
n *= w;
}
template <typename T>
inline void exg(T &a, T &b) {
a ^= b ^= a ^= b;
}
template <typename T>
inline void chkmn(T &a, const T &b) {
(a > b) && (a = b);
}
template <typename T>
inline void chkmx(T &a, const T &b) {
(a < b) && (a = b);
}
inline int min(const int &a, const int &b) { return a < b ? a : b; }
inline int max(const int &a, const int &b) { return a > b ? a : b; }
inline long long min(const long long &a, const long long &b) {
return a < b ? a : b;
}
inline long long max(const long long &a, const long long &b) {
return a > b ? a : b;
}
int MOD;
inline int adt(const int &a) { return (a % MOD + MOD) % MOD; }
inline int inc(const int &a, const int &b) {
return a + b >= MOD ? a + b - MOD : a + b;
}
inline int dec(const int &a, const int &b) {
return a - b < 0 ? a - b + MOD : a - b;
}
inline int mul(const int &a, const int &b) { return 1LL * a * b % MOD; }
inline int sqr(const int &a) { return 1LL * a * a % MOD; }
inline int cub(const int &a) { return 1LL * a * a % MOD * a % MOD; }
inline void Adt(int &a) { a = (a % MOD + MOD) % MOD; }
inline void Inc(int &a, const int &b) { ((a += b) >= MOD) && (a -= MOD); }
inline void Dec(int &a, const int &b) { ((a -= b) < 0) && (a += MOD); }
inline void Mul(int &a, const int &b) { a = 1LL * a * b % MOD; }
inline void Sqr(int &a) { a = 1LL * a * a % MOD; }
inline void Cub(int &a) { a = 1LL * a * a % MOD * a % MOD; }
inline int fsp(int a, int x = MOD - 2) {
int res = 1;
while (x) {
if (x & 1) Mul(res, a);
Sqr(a), x >>= 1;
}
return res;
}
const int maxn = 4e5 + 5;
int T, n, k, tot;
int pa[maxn], rk[maxn], mn[maxn], r[maxn];
vector<int> h[maxn], g[maxn];
map<int, int> pp;
struct bomb {
int x, y, t;
} b[maxn];
inline bool Cmp_1(int x, int y) { return b[x].y < b[y].y; }
inline bool Cmp_2(int x, int y) { return b[x].x < b[y].x; }
inline int Find(int x) { return (pa[x] ^ x) ? pa[x] = Find(pa[x]) : x; }
inline bool Judge(int x, int y) { return Find(x) == Find(y); }
inline void Merge(int x, int y) {
x = Find(x), y = Find(y);
if (rk[x] > rk[y]) exg(x, y);
pa[x] = y, chkmn(mn[y], mn[x]);
if (rk[x] == rk[y]) ++rk[y];
}
int main() {
read(T);
while (T--) {
read(n), read(k);
tot = 0, pp.clear();
for (int i = (1); i <= (n); ++i) {
read(b[i].x), read(b[i].y), read(b[i].t), pa[i] = i, rk[i] = 0,
mn[i] = b[i].t;
if (!pp.count(b[i].x)) pp[b[i].x] = ++tot;
if (!pp.count(b[i].y)) pp[b[i].y] = ++tot;
h[pp[b[i].x]].emplace_back(i), g[pp[b[i].y]].emplace_back(i);
}
for (int i = (1); i <= (tot); ++i) {
sort(h[i].begin(), h[i].end(), Cmp_1);
sort(g[i].begin(), g[i].end(), Cmp_2);
for (int j = (1); j <= ((int)h[i].size() - 1); ++j)
if (b[h[i][j]].y - b[h[i][j - 1]].y <= k &&
!Judge(h[i][j], h[i][j - 1]))
Merge(h[i][j], h[i][j - 1]);
for (int j = (1); j <= ((int)g[i].size() - 1); ++j)
if (b[g[i][j]].x - b[g[i][j - 1]].x <= k &&
!Judge(g[i][j], g[i][j - 1]))
Merge(g[i][j], g[i][j - 1]);
h[i].clear(), g[i].clear();
}
tot = 0;
for (int i = (1); i <= (n); ++i)
if (Find(i) == i) r[++tot] = mn[i];
sort(r + 1, r + tot + 1);
int L = 1, R = tot, t = 0;
while (L <= R) {
--R;
while (L <= R && r[L] == t) ++L;
if (L > R) printf("%d\n", t);
++t;
}
}
return 0;
}
|
You are given a permutation p of n elements. A permutation of n elements is an array of length n containing each integer from 1 to n exactly once. For example, [1, 2, 3] and [4, 3, 5, 1, 2] are permutations, but [1, 2, 4] and [4, 3, 2, 1, 2] are not permutations. You should perform q queries.
There are two types of queries:
* 1 x y — swap p_x and p_y.
* 2 i k — print the number that i will become if we assign i = p_i k times.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 10^5).
The second line contains n integers p_1, p_2, ..., p_n.
Each of the next q lines contains three integers. The first integer is t (1 ≤ t ≤ 2) — type of query. If t = 1, then the next two integers are x and y (1 ≤ x, y ≤ n; x ≠ y) — first-type query. If t = 2, then the next two integers are i and k (1 ≤ i, k ≤ n) — second-type query.
It is guaranteed that there is at least one second-type query.
Output
For every second-type query, print one integer in a new line — answer to this query.
Examples
Input
5 4
5 3 4 2 1
2 3 1
2 1 2
1 1 3
2 1 2
Output
4
1
2
Input
5 9
2 3 5 1 4
2 3 5
2 5 5
2 5 1
2 5 3
2 5 4
1 5 4
2 5 3
2 2 5
2 5 1
Output
3
5
4
2
3
3
3
1
Note
In the first example p = \{5, 3, 4, 2, 1\}.
The first query is to print p_3. The answer is 4.
The second query is to print p_{p_1}. The answer is 1.
The third query is to swap p_1 and p_3. Now p = \{4, 3, 5, 2, 1\}.
The fourth query is to print p_{p_1}. The answer is 2. | import sys
raw_input = iter(sys.stdin.read().splitlines()).next
class Node(object):
def __init__(self, v):
self.v = v
self.children = [None]*2
self.parent = None
self.size = 1
def pull(self):
self.size = 1
if self.children[0]:
self.size += self.children[0].size
if self.children[1] :
self.size += self.children[1].size
def rotate(self):
q = self.parent
x = not self.pos()
q.children[not x] = self.children[x]
if self.children[x]:
self.children[x].parent = q
self.parent = q.parent
if q.parent:
q.parent.children[q.pos()] = self
self.children[x] = q
q.parent = self
q.pull()
def pos(self):
return self.parent.children[1] == self
def splay(self, g=None):
while self.parent != g:
if self.parent.parent != g:
if self.pos() == self.parent.pos():
self.parent.rotate()
else:
self.rotate()
self.rotate()
self.pull()
def select(t, k):
if t.children[0]:
if k < t.children[0].size:
return select(t.children[0], k)
else:
k -= t.children[0].size
if k == 0:
return t
k -= 1
return select(t.children[1], k)
def build(v, left, right, nodes):
if left > right:
return None
mid = left + (right-left)//2
u = v[mid]
nodes[u] = Node(u)
nodes[u].children[0] = build(v, left , mid-1, nodes)
nodes[u].children[1] = build(v, mid+1, right, nodes)
for i in xrange(2):
if nodes[u].children[i]:
nodes[u].children[i].parent = nodes[u]
nodes[u].pull()
return nodes[u]
def cano(u):
if not u.children[1]:
return
rm = select(u.children[1], 0)
rm.splay(u)
u.children[1] = None
rm.parent = None
u.pull()
rt = select(u, 0)
rt.splay()
rt.children[0] = rm
rm.parent = rt
rt.pull()
u.splay()
assert(not u.children[1])
def solution():
n, q = map(int, raw_input().strip().split())
p = map(lambda x: int(x)-1, raw_input().strip().split())
nodes = [None]*n
lookup = [False]*n
for i in xrange(n):
if lookup[i]:
continue
j = i
v = []
while not lookup[j]:
v.append(j)
lookup[j] = True
j = p[j]
build(v, 0, len(v)-1, nodes)
result = []
for _ in xrange(q):
op, x, y = map(int, raw_input().strip().split())
x -= 1
if op == 1:
y -= 1
u, v = nodes[x], nodes[y]
u.splay()
cano(u)
v.splay()
if not u.parent:
cano(v)
u.children[1] = v
v.parent = u
u.pull()
else:
v.children[1].parent = None
v.children[1] = None
v.pull()
else:
u = nodes[x]
u.splay()
s = u.size
j = u.children[0].size if u.children[0] else 0
j = (j+y) % s
u = select(u, j)
u.splay()
result.append(u.v+1)
return "\n".join(map(str, result))
print '%s' % solution() |
You had n positive integers a_1, a_2, ..., a_n arranged in a circle. For each pair of neighboring numbers (a_1 and a_2, a_2 and a_3, ..., a_{n - 1} and a_n, and a_n and a_1), you wrote down: are the numbers in the pair equal or not.
Unfortunately, you've lost a piece of paper with the array a. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array a which is consistent with information you have about equality or non-equality of corresponding pairs?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Next t cases follow.
The first and only line of each test case contains a non-empty string s consisting of characters E and/or N. The length of s is equal to the size of array n and 2 ≤ n ≤ 50. For each i from 1 to n:
* if s_i = E then a_i is equal to a_{i + 1} (a_n = a_1 for i = n);
* if s_i = N then a_i is not equal to a_{i + 1} (a_n ≠ a_1 for i = n).
Output
For each test case, print YES if it's possible to choose array a that are consistent with information from s you know. Otherwise, print NO.
It can be proved, that if there exists some array a, then there exists an array a of positive integers with values less or equal to 10^9.
Example
Input
4
EEE
EN
ENNEENE
NENN
Output
YES
NO
YES
YES
Note
In the first test case, you can choose, for example, a_1 = a_2 = a_3 = 5.
In the second test case, there is no array a, since, according to s_1, a_1 is equal to a_2, but, according to s_2, a_2 is not equal to a_1.
In the third test case, you can, for example, choose array a = [20, 20, 4, 50, 50, 50, 20].
In the fourth test case, you can, for example, choose a = [1, 3, 3, 7]. |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringJoiner;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringJoiner sj = new StringJoiner("\n");
for (int i = 0; i < t; i++) {
String answer = singleCase(br);
sj.add(answer);
}
System.out.println(sj);
}
static String singleCase(BufferedReader br) throws IOException {
String line = br.readLine();
int n = 0;
for (int i = 0; i < line.length(); i++) {
String k = line.substring(i, i + 1);
if (k.equals("N")) {
n++;
if (n > 1) {
return "YES";
}
}
}
return n == 1 ? "NO" : "YES";
}
}
|
A rectangle with its opposite corners in (0, 0) and (w, h) and sides parallel to the axes is drawn on a plane.
You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.
Your task is to choose three points in such a way that:
* exactly two of them belong to the same side of a rectangle;
* the area of a triangle formed by them is maximum possible.
Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.
The first line of each testcase contains two integers w and h (3 ≤ w, h ≤ 10^6) — the coordinates of the corner of a rectangle.
The next two lines contain the description of the points on two horizontal sides. First, an integer k (2 ≤ k ≤ 2 ⋅ 10^5) — the number of points. Then, k integers x_1 < x_2 < ... < x_k (0 < x_i < w) — the x coordinates of the points in the ascending order. The y coordinate for the first line is 0 and for the second line is h.
The next two lines contain the description of the points on two vertical sides. First, an integer k (2 ≤ k ≤ 2 ⋅ 10^5) — the number of points. Then, k integers y_1 < y_2 < ... < y_k (0 < y_i < h) — the y coordinates of the points in the ascending order. The x coordinate for the first line is 0 and for the second line is w.
The total number of points on all sides in all testcases doesn't exceed 2 ⋅ 10^5.
Output
For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.
Example
Input
3
5 8
2 1 2
3 2 3 4
3 1 4 6
2 4 5
10 7
2 3 9
2 1 7
3 1 3 4
3 4 5 6
11 5
3 1 6 8
3 3 6 8
3 1 3 4
2 2 4
Output
25
42
35
Note
The points in the first testcase of the example:
* (1, 0), (2, 0);
* (2, 8), (3, 8), (4, 8);
* (0, 1), (0, 4), (0, 6);
* (5, 4), (5, 5).
The largest triangle is formed by points (0, 1), (0, 6) and (5, 4) — its area is 25/2. Thus, the doubled area is 25. Two points that are on the same side are: (0, 1) and (0, 6). | import java.util.*;
import java.io.*;
import java.lang.*;
// Problem - Multiples of 3 onn codeforces MNedium difficulty level
// or check on youtube channel CodeNCode
public class Problem {
static int Mod = 1000000007;
static long dp[][];
static int g[][];
static int fact[];
public static void main(String[] args) {
MyScanner scan = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = scan.nextInt();
// int t = 1;
while (t-- > 0) {
long w= scan.nextLong();
long h= scan.nextLong();
int k1= scan.nextInt();
long a1[]= new long[k1];
for(int i=0;i<k1;i++)
a1[i]= scan.nextLong();
long ans= Long.MIN_VALUE;
ans= Math.max(ans, (a1[k1-1]-a1[0])*h);
int k2= scan.nextInt();
long a2[]= new long[k2];
for(int i=0;i<k2;i++)
a2[i]= scan.nextLong();
ans= Math.max(ans, (a2[k2-1]-a2[0])*h);
int k3= scan.nextInt();
long a3[]= new long[k3];
for(int i=0;i<k3;i++)
a3[i]= scan.nextLong();
ans= Math.max(ans, (a3[k3-1]-a3[0])*w);
int k4= scan.nextInt();
long a4[]= new long[k4];
for(int i=0;i<k4;i++)
a4[i]= scan.nextLong();
ans= Math.max(ans, (a4[k4-1]-a4[0])*w);
out.println(ans);
}
out.close();
}
static ArrayList<Integer> digits(int n){
ArrayList<Integer> list= new ArrayList<>();
while(n>0){
list.add(n%10);
n=n/10;
}
Collections.reverse(list);
return list;
}
static class Pair {
int l;
int r;
Pair(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + l;
result = prime * result + r;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (l != other.l)
return false;
if (r != other.r)
return false;
return true;
}
@Override
public String toString() {
return "Pair [l=" + l + ", r=" + r + "]";
}
}
public static void reverse(int a[]) {
int n = a.length;
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
public static void sort(int[] array) {
ArrayList<Integer> copy = new ArrayList<>();
for (Integer i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
public static void sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (Long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b); // gcd(a,b) = gcd(a-b,b) or gcd(a,b) = gcd(b,a%b) where a>b
}
public static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static long power(long x, long y) {
long temp;
if (y == 0) // a^b= (a^b/2)^2 if b is even
return 1; // = (a*a^(b-1)) if b is odd
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
static long mod(long x) {
return ((x % Mod + Mod) % Mod);
}
static long add(long a, long b) {
return mod(mod(a) + mod(b));
}
static int mod(int x) {
return ((x % Mod + Mod) % Mod);
}
static int add(int a, int b) {
return mod(mod(a) + mod(b));
}
static int sub(int a, int b) {
return mod(mod(a) - mod(b) + Mod);
}
static long mul(long a, long b) {
return mod(mod(a) * mod(b));
}
static long pow(long x, long y, long p) {
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long modInverse(long a, long m) {
// int g = gcd(a, m);
// if (g != 1)
// System.out.println("Inverse doesn't exist");
// else {
// // If a and m are relatively prime, then modulo
// // inverse is a^(m-2) mode m
// return power(a, m - 2, m);
// }
return pow(a, m - 2, m);
}
}
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 an integer k and a string s that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).
Each asterisk should be replaced with several (from 0 to k inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.
The result of the replacement is called a BA-string.
Two strings a and b are different if they either have different lengths or there exists such a position i that a_i ≠ b_i.
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.
Now consider all different BA-strings and find the x-th lexicographically smallest of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of testcases.
The first line of each testcase contains three integers n, k and x (1 ≤ n ≤ 2000; 0 ≤ k ≤ 2000; 1 ≤ x ≤ 10^{18}). n is the length of string s.
The second line of each testcase is a string s. It consists of n characters, each of them is either 'a' (a lowercase Latin letter) or '*' (an asterisk).
The sum of n over all testcases doesn't exceed 2000. For each testcase x doesn't exceed the total number of different BA-strings. String s contains at least one character 'a'.
Output
For each testcase, print a single string, consisting only of characters 'b' and 'a' (lowercase Latin letters) — the x-th lexicographically smallest BA-string.
Example
Input
3
2 4 3
a*
4 1 3
a**a
6 3 20
**a***
Output
abb
abba
babbbbbbbbb
Note
In the first testcase of the example, BA-strings ordered lexicographically are:
1. a
2. ab
3. abb
4. abbb
5. abbbb
In the second testcase of the example, BA-strings ordered lexicographically are:
1. aa
2. aba
3. abba
Note that string "aba" is only counted once, even though there are two ways to replace asterisks with characters 'b' to get it. | def solution(n, k, x, s):
current_len = 0
astrics = []
for c in s:
if c == '*':
current_len += 1
elif c == 'a':
if current_len != 0:
astrics.append(current_len)
current_len = 0
if current_len != 0:
astrics.append(current_len)
astrics = list(map(lambda y: k*y+1, astrics))
x -= 1
result = []
for num in reversed(astrics):
m = x % num
x //= num
result.append(m)
answer = ''
c = s[0]
if c == 'a':
answer = 'a'
for i in range(1, n):
if s[i] == 'a' and s[i - 1] == '*':
num = result.pop()
answer += num * 'b'
if s[i] == 'a':
answer += 'a'
if s[n - 1] == '*':
num = result.pop()
answer += num * 'b'
return answer
if __name__ == '__main__':
t = int(input())
for i in range(t):
n, k, x = list(map(int, input().split()))
s = input()
print(solution(n, k, x, s))
|
One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of n different flavors. A bag of the i-th flavor costs a_i burles.
The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan:
1. you have only coins of 1, 2 and 3 burles;
2. since it's morning, the store will ask you to pay in exact change, i. e. if you choose the i-th flavor, you'll have to pay exactly a_i burles.
Coins are heavy, so you'd like to take the least possible number of coins in total. That's why you are wondering: what is the minimum total number of coins you should take with you, so you can buy a bag of chips of any flavor in exact change?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains the single integer n (1 ≤ n ≤ 100) — the number of flavors in the store.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the cost of one bag of each flavor.
Output
For each test case, print one integer — the minimum number of coins you need to buy one bag of any flavor you'll choose in exact change.
Example
Input
4
1
1337
3
10 8 10
5
1 2 3 4 5
3
7 77 777
Output
446
4
3
260
Note
In the first test case, you should, for example, take with you 445 coins of value 3 and 1 coin of value 2. So, 1337 = 445 ⋅ 3 + 1 ⋅ 2.
In the second test case, you should, for example, take 2 coins of value 3 and 2 coins of value 2. So you can pay either exactly 8 = 2 ⋅ 3 + 1 ⋅ 2 or 10 = 2 ⋅ 3 + 2 ⋅ 2.
In the third test case, it's enough to take 1 coin of value 3 and 2 coins of value 1. | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int answer = 1e9;
for (int x = 0; x <= 2; x++) {
for (int y = 0; y <= 2; y++) {
int result = 0;
for (int i = 0; i < n; i++) {
int tmp = 1e9;
for (int sx = 0; sx <= x; sx++) {
for (int sy = 0; sy <= y; sy++) {
int v = a[i] - sx - 2 * sy;
if (v >= 0 && v % 3 == 0) {
tmp = min(tmp, v / 3);
}
}
}
result = max(result, tmp);
}
answer = min(answer, result + x + y);
}
}
cout << answer << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tests;
cin >> tests;
while (tests--) {
solve();
}
return 0;
}
|
You have an array of integers (initially empty).
You have to perform q queries. Each query is of one of two types:
* "1 x" — add the element x to the end of the array;
* "2 x y" — replace all occurrences of x in the array with y.
Find the resulting array after performing all the queries.
Input
The first line contains a single integer q (1 ≤ q ≤ 5 ⋅ 10^5) — the number of queries.
Next q lines contain queries (one per line). Each query is of one of two types:
* "1 x" (1 ≤ x ≤ 5 ⋅ 10^5);
* "2 x y" (1 ≤ x, y ≤ 5 ⋅ 10^5).
It's guaranteed that there is at least one query of the first type.
Output
In a single line, print k integers — the resulting array after performing all the queries, where k is the number of queries of the first type.
Examples
Input
7
1 3
1 1
2 1 2
1 2
1 1
1 2
2 1 3
Output
3 2 2 3 2
Input
4
1 1
1 2
1 1
2 2 2
Output
1 2 1
Input
8
2 1 4
1 1
1 4
1 2
2 2 4
2 4 3
1 2
2 2 7
Output
1 3 3 7
Note
In the first example, the array changes as follows:
[] → [3] → [3, 1] → [3, 2] → [3, 2, 2] → [3, 2, 2, 1] → [3, 2, 2, 1, 2] → [3, 2, 2, 3, 2].
In the second example, the array changes as follows:
[] → [1] → [1, 2] → [1, 2, 1] → [1, 2, 1].
In the third example, the array changes as follows:
[] → [] → [1] → [1, 4] → [1, 4, 2] → [1, 4, 4] → [1, 3, 3] → [1, 3, 3, 2] → [1, 3, 3, 7]. | from collections import *
import sys
import io, os
import math
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
def ceil(a, b):
a = -a
k = a // b
k = -k
return k
# arr=list(map(int, input().split()))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def strinp(testcases):
k = 5
if (testcases == -1 or testcases == 1):
k = 1
f = str(input())
f = f[2:len(f) - k]
return f
def main():
q=int(input())
ans=[]
iden=[i for i in range((5*(10**5))+1)]
quer=[]
for _ in range(q):
arr=list(map(int, input().split()))
quer.append(arr)
arr=[]
for i in range(q-1,-1,-1):
if(quer[i][0]==1):
arr.append(iden[quer[i][1]])
continue
iden[quer[i][1]]=iden[quer[i][2]]
arr.reverse()
print(*arr)
main() |
You are given a permutation p consisting of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once).
Let's call an array a bipartite if the following undirected graph is bipartite:
* the graph consists of n vertices;
* two vertices i and j are connected by an edge if i < j and a_i > a_j.
Your task is to find a bipartite array of integers a of size n, such that a_i = p_i or a_i = -p_i, or report that no such array exists. If there are multiple answers, print any of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^6) — the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n.
The sum of n over all test cases doesn't exceed 10^6.
Output
For each test case, print the answer in the following format. If such an array a does not exist, print "NO" in a single line. Otherwise, print "YES" in the first line and n integers — array a in the second line.
Example
Input
4
3
1 2 3
6
1 3 2 6 5 4
4
4 1 3 2
8
3 2 1 6 7 8 5 4
Output
YES
1 2 3
NO
YES
-4 -1 -3 -2
YES
-3 -2 1 6 7 -8 -5 -4 | #include <bits/stdc++.h>
using namespace std;
long long a[1000005], dp[1000005][2];
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
long long T;
cin >> T;
while (T--) {
long long n;
cin >> n;
for (long long i = 1; i <= n; i++) cin >> a[i];
a[0] = 1e9, dp[0][0] = -1e9;
for (long long i = 1; i <= n; i++) dp[i][0] = dp[i][1] = 1e9;
for (long long i = 1; i <= n; i++) {
long long x = -a[i - 1], y = dp[i - 1][0];
if (a[i] > x) dp[i][1] = min(dp[i][1], y);
if (a[i] > y) dp[i][1] = min(dp[i][1], x);
if (-a[i] > x) dp[i][0] = min(dp[i][0], y);
if (-a[i] > y) dp[i][0] = min(dp[i][0], x);
x = a[i - 1], y = dp[i - 1][1];
if (a[i] > x) dp[i][1] = min(dp[i][1], y);
if (a[i] > y) dp[i][1] = min(dp[i][1], x);
if (-a[i] > x) dp[i][0] = min(dp[i][0], y);
if (-a[i] > y) dp[i][0] = min(dp[i][0], x);
}
if (dp[n][1] <= n || dp[n][0] <= n) {
cout << "YES\n";
long long now = 0;
if (dp[n][1] <= n) now = 1;
for (long long i = n; i >= 1; i--) {
if (now == 1) {
long long x = -a[i - 1], y = dp[i - 1][0];
if (a[i] > x && dp[i][1] == y) now = 0;
if (a[i] > y && dp[i][1] == x) now = 0;
x = a[i - 1], y = dp[i - 1][1];
if (a[i] > x && dp[i][1] == y) now = 1;
if (a[i] > y && dp[i][1] == x) now = 1;
} else {
long long x = -a[i - 1], y = dp[i - 1][0];
if (-a[i] > x && dp[i][0] == y) now = 0;
if (-a[i] > y && dp[i][0] == x) now = 0;
x = a[i - 1], y = dp[i - 1][1];
if (-a[i] > x && dp[i][0] == y) now = 1;
if (-a[i] > y && dp[i][0] == x) now = 1;
a[i] = -a[i];
}
}
for (long long i = 1; i <= n; i++) cout << a[i] << " ";
cout << "\n";
} else
cout << "NO\n";
}
return 0;
}
|
For a sequence of strings [t_1, t_2, ..., t_m], let's define the function f([t_1, t_2, ..., t_m]) as the number of different strings (including the empty string) that are subsequences of at least one string t_i. f([]) = 0 (i. e. the number of such strings for an empty sequence is 0).
You are given a sequence of strings [s_1, s_2, ..., s_n]. Every string in this sequence consists of lowercase Latin letters and is sorted (i. e., each string begins with several (maybe zero) characters a, then several (maybe zero) characters b, ..., ends with several (maybe zero) characters z).
For each of 2^n subsequences of [s_1, s_2, ..., s_n], calculate the value of the function f modulo 998244353.
Input
The first line contains one integer n (1 ≤ n ≤ 23) — the number of strings.
Then n lines follow. The i-th line contains the string s_i (1 ≤ |s_i| ≤ 2 ⋅ 10^4), consisting of lowercase Latin letters. Each string s_i is sorted.
Output
Since printing up to 2^{23} integers would be really slow, you should do the following:
For each of the 2^n subsequences (which we denote as [s_{i_1}, s_{i_2}, ..., s_{i_k}]), calculate f([s_{i_1}, s_{i_2}, ..., s_{i_k}]), take it modulo 998244353, then multiply it by k ⋅ (i_1 + i_2 + ... + i_k). Print the XOR of all 2^n integers you get.
The indices i_1, i_2, ..., i_k in the description of each subsequences are 1-indexed (i. e. are from 1 to n).
Examples
Input
3
a
b
c
Output
92
Input
2
aa
a
Output
21
Input
2
a
a
Output
10
Input
2
abcd
aabb
Output
124
Input
3
ddd
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaabbbbbbbbbbbcccccccccccciiiiiiiiiiiiiiiiiiiiiiooooooooooqqqqqqqqqqqqqqqqqqvvvvvzzzzzzzzzzzz
Output
15706243380 | #include <bits/stdc++.h>
using namespace std;
long long mod = 998244353;
long double pi = 3.141592653589793238;
void pls() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int dp[(1 << 23)];
int arr[23][26];
int mul(long long a, long long b) { return (a % mod * b % mod) % mod; }
void solve() {
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < s.size(); j++) arr[i][(s[j] - 'a')]++;
}
int cur[26];
for (int i = 1; i < (1 << n); i++) {
for (int k = 0; k < 26; k++) cur[k] = INT_MAX;
int bit = 0;
for (int j = 0; j < n; j++) {
if (i & (1 << j)) {
for (int k = 0; k < 26; k++) cur[k] = min(cur[k], arr[j][k]);
bit++;
}
}
int ans = 1;
for (int i = 0; i < 26; i++) ans = mul(ans, cur[i] + 1);
if (bit & 1)
dp[i] = ans;
else
dp[i] = (mod - ans) % mod;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < (1 << n); j++) {
if (j & (1 << i)) {
{
dp[j] += dp[j ^ (1 << i)];
dp[j] %= mod;
}
}
}
}
long long res = 0;
for (int i = 0; i < (1 << n); i++) {
long long cur = 0;
long long kk = 0;
long long sum = 0;
for (int j = 0; j < n; j++)
if (i & (1 << j)) kk++, sum += (j + 1);
cur = dp[i] * kk * sum;
res = res ^ cur;
}
cout << res << "\n";
}
}
int main() {
pls();
solve();
return 0;
}
|
There are three sticks with integer lengths l_1, l_2 and l_3.
You are asked to break exactly one of them into two pieces in such a way that:
* both pieces have positive (strictly greater than 0) integer length;
* the total length of the pieces is equal to the original length of the stick;
* it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides.
A square is also considered a rectangle.
Determine if it's possible to do that.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.
The only line of each testcase contains three integers l_1, l_2, l_3 (1 ≤ l_i ≤ 10^8) — the lengths of the sticks.
Output
For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).
Example
Input
4
6 1 5
2 5 2
2 4 2
5 5 4
Output
YES
NO
YES
YES
Note
In the first testcase, the first stick can be broken into parts of length 1 and 5. We can construct a rectangle with opposite sides of length 1 and 5.
In the second testcase, breaking the stick of length 2 can only result in sticks of lengths 1, 1, 2, 5, which can't be made into a rectangle. Breaking the stick of length 5 can produce results 2, 3 or 1, 4 but neither of them can't be put into a rectangle.
In the third testcase, the second stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 2 (which is a square).
In the fourth testcase, the third stick can be broken into parts of length 2 and 2. The resulting rectangle has opposite sides 2 and 5. | import java.io.*;
import java.util.*;
/*
*/
public class A{
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int t=sc.nextInt();
for(int tt=0;tt<t;tt++) {
int s[]=sc.readArray(3);
ruffleSort(s);
if((s[0]+s[1]+s[2])%2==1) {
System.out.println("NO");
continue;
}
if(s[0]+s[1]==s[2]) {
System.out.println("YES");
continue;
}
if(s[0]==s[1] || s[1]==s[2]) {
System.out.println("YES");
continue;
}
System.out.println("NO");
}
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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 nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
|
Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.
So imagine Monocarp got recommended n songs, numbered from 1 to n. The i-th song had its predicted rating equal to p_i, where 1 ≤ p_i ≤ n and every integer from 1 to n appears exactly once. In other words, p is a permutation.
After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string s, such that s_i=0 means that he disliked the i-th song, and s_i=1 means that he liked it.
Now the service has to re-evaluate the song ratings in such a way that:
* the new ratings q_1, q_2, ..., q_n still form a permutation (1 ≤ q_i ≤ n; each integer from 1 to n appears exactly once);
* every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all i, j such that s_i=1 and s_j=0, q_i>q_j should hold).
Among all valid permutations q find the one that has the smallest value of ∑_{i=1}^n |p_i-q_i|, where |x| is an absolute value of x.
Print the permutation q_1, q_2, ..., q_n. If there are multiple answers, you can print any of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.
The first line of each testcase contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of songs.
The second line of each testcase contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n) — the permutation of the predicted ratings.
The third line contains a single string s, consisting of n characters. Each character is either a 0 or a 1. 0 means that Monocarp disliked the song, and 1 means that he liked it.
The sum of n over all testcases doesn't exceed 2 ⋅ 10^5.
Output
For each testcase, print a permutation q — the re-evaluated ratings of the songs. If there are multiple answers such that ∑_{i=1}^n |p_i-q_i| is minimum possible, you can print any of them.
Example
Input
3
2
1 2
10
3
3 1 2
111
8
2 3 1 8 5 4 7 6
01110001
Output
2 1
3 1 2
1 6 5 8 3 2 4 7
Note
In the first testcase, there exists only one permutation q such that each liked song is rating higher than each disliked song: song 1 gets rating 2 and song 2 gets rating 1. ∑_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2.
In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to p. Its cost is 0. | for i in range(int(input())):
n, p, s = int(input()), [int(i) for i in input().split()], input()
p = sorted(zip(s, p, range(n)))
w = [0] * n
for i in range(n):
w[p[i][2]] = i + 1
print(*w)
zip() |
You are given an integer array a_1, a_2, ..., a_n and integer k.
In one step you can
* either choose some index i and decrease a_i by one (make a_i = a_i - 1);
* or choose two indices i and j and set a_i equal to a_j (make a_i = a_j).
What is the minimum number of steps you need to make the sum of array ∑_{i=1}^{n}{a_i} ≤ k? (You are allowed to make values of array negative).
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^{15}) — the size of array a and upper bound on its sum.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the array itself.
It's guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of steps to make ∑_{i=1}^{n}{a_i} ≤ k.
Example
Input
4
1 10
20
2 69
6 9
7 8
1 2 1 3 1 2 1
10 1
1 2 3 1 2 6 1 6 8 10
Output
10
0
2
7
Note
In the first test case, you should decrease a_1 10 times to get the sum lower or equal to k = 10.
In the second test case, the sum of array a is already less or equal to 69, so you don't need to change it.
In the third test case, you can, for example:
1. set a_4 = a_3 = 1;
2. decrease a_4 by one, and get a_4 = 0.
As a result, you'll get array [1, 2, 1, 0, 1, 2, 1] with sum less or equal to 8 in 1 + 1 = 2 steps.
In the fourth test case, you can, for example:
1. choose a_7 and decrease in by one 3 times; you'll get a_7 = -2;
2. choose 4 elements a_6, a_8, a_9 and a_{10} and them equal to a_7 = -2.
As a result, you'll get array [1, 2, 3, 1, 2, -2, -2, -2, -2, -2] with sum less or equal to 1 in 3 + 4 = 7 steps. | import sys
import os.path
from collections import *
import math
import bisect
import heapq as hq
from fractions import Fraction
from random import randint
if os.path.exists("input.txt"):
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
input = sys.stdin.readline
##########################################################
def solve():
n,k = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
x = sum(arr)
if(sum(arr) <= k):
print(0)
return
arr.sort()
pos = 0
Sum = 0
res = 1e16
while pos < n:
Sum += arr[pos]
x = (Sum - arr[0])
# print(x)
x = k - x
y = n - pos
z = min(x // y, arr[0])
# print(Sum,x,y,z)
res = min(res, arr[0] - z + y - 1)
pos += 1
print(res)
t = int(input())
while t:
t -= 1
solve()
##########################################################
|
You are given a binary string (i. e. a string consisting of characters 0 and/or 1) s of length n. You can perform the following operation with the string s at most once: choose a substring (a contiguous subsequence) of s having exactly k characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).
Calculate the number of different strings which can be obtained from s by performing this operation at most once.
Input
The first line contains two integers n and k (2 ≤ n ≤ 5000; 0 ≤ k ≤ n).
The second line contains the string s of length n, consisting of characters 0 and/or 1.
Output
Print one integer — the number of different strings which can be obtained from s by performing the described operation at most once. Since the answer can be large, output it modulo 998244353.
Examples
Input
7 2
1100110
Output
16
Input
5 0
10010
Output
1
Input
8 1
10001000
Output
10
Input
10 8
0010011000
Output
1
Note
Some strings you can obtain in the first example:
* to obtain 0110110, you can take the substring from the 1-st character to the 4-th character, which is 1100, and reorder its characters to get 0110;
* to obtain 1111000, you can take the substring from the 3-rd character to the 7-th character, which is 00110, and reorder its characters to get 11000;
* to obtain 1100101, you can take the substring from the 5-th character to the 7-th character, which is 110, and reorder its characters to get 101.
In the second example, k = 0 so you can only choose the substrings consisting only of 0 characters. Reordering them doesn't change the string at all, so the only string you can obtain is 10010. | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 9;
const long long MOD = 1e9 + 7;
const int mod = 998244353;
inline long long qpow(long long b, long long e, long long m) {
long long a = 1;
for (; e; e >>= 1, b = b * b % m)
if (e & 1) a = a * b % m;
return a;
}
long long exgcd(long long a, long long b, long long &x, long long &y) {
if (b == 0) {
x = 1, y = 0;
return a;
}
long long d = exgcd(b, a % b, x, y);
long long z = x;
x = y, y = z - y * (a / b);
return d;
}
char s[maxn];
long long C[5009][5009];
void init() {
C[0][0] = 1;
for (int i = 1; i <= 5000; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j++) {
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
C[i][j] %= mod;
}
}
}
vector<int> ve;
int main() {
init();
int n, k;
scanf("%d%d", &n, &k);
scanf("%s", s + 1);
if (k == 0) {
cout << "1" << '\n';
return 0;
}
ve.push_back(0);
for (int i = 1; i <= n; i++) {
if (s[i] == '1') ve.push_back(i);
}
ve.push_back(n + 1);
if (ve.size() - 2 < k) {
cout << 1 << '\n';
return 0;
}
long long ans = 0;
for (int i = 1;; i++) {
if (i + k >= ve.size()) break;
ans += C[ve[i + k] - ve[i - 1] - 1][k];
if (i + k < (int)ve.size() - 1) ans -= C[ve[i + k] - ve[i] - 1][k - 1];
ans %= mod;
}
ans = (ans % mod + mod) % mod;
cout << ans << '\n';
}
|
Petya is a math teacher. n of his students has written a test consisting of m questions. For each student, it is known which questions he has answered correctly and which he has not.
If the student answers the j-th question correctly, he gets p_j points (otherwise, he gets 0 points). Moreover, the points for the questions are distributed in such a way that the array p is a permutation of numbers from 1 to m.
For the i-th student, Petya knows that he expects to get x_i points for the test. Petya wonders how unexpected the results could be. Petya believes that the surprise value of the results for students is equal to ∑_{i=1}^{n} |x_i - r_i|, where r_i is the number of points that the i-th student has got for the test.
Your task is to help Petya find such a permutation p for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10; 1 ≤ m ≤ 10^4) — the number of students and the number of questions, respectively.
The second line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ (m(m+1))/(2)), where x_i is the number of points that the i-th student expects to get.
This is followed by n lines, the i-th line contains the string s_i (|s_i| = m; s_{i, j} ∈ \{0, 1\}), where s_{i, j} is 1 if the i-th student has answered the j-th question correctly, and 0 otherwise.
The sum of m for all test cases does not exceed 10^4.
Output
For each test case, print m integers — a permutation p for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.
Example
Input
3
4 3
5 1 2 2
110
100
101
100
4 4
6 2 0 10
1001
0010
0110
0101
3 6
20 3 15
010110
000101
111111
Output
3 1 2
2 3 4 1
3 1 4 5 2 6 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
/*
e = expected, a = actual
e_1 - a_1
a_2 - e_2
e_3 - a_3
================
-a_1 +a_2 -a_3 => maximize
+e_1 -e_2 +e_3 => constant
Each person is either + per question or - per question
sort the question by their net score
questionValue*timesCounted
2^10 * 1024 * log
1
4 4
6 2 0 10
1001
0010
0110
0101
I say 4 3 1 2
answer 2 3 4 1
Expect: 6 2 0 10
Me: Get 6 1 4 5
Him: 3 4 7 4
*/
public class E {
static boolean[][] personGotQuestion;
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int nPeople=fs.nextInt();
int nQuestions=fs.nextInt();
int[] expectedScores=fs.readArray(nPeople);
personGotQuestion=new boolean[nPeople][nQuestions];
for (int person=0; person<nPeople; person++) {
char[] line=fs.next().toCharArray();
for (int q=0; q<nQuestions; q++)
personGotQuestion[person][q]=line[q]=='1';
}
ArrayList<Integer>[] count=new ArrayList[1<<nPeople];
for (int q=0; q<nQuestions; q++) {
int mask=0;
for (int p=0; p<nPeople; p++)
mask+=(1<<p)*(personGotQuestion[p][q]?1:0);
if (count[mask]==null) count[mask]=new ArrayList<>();
count[mask].add(q);
}
int nNonzero=0;
for (ArrayList<Integer> l:count) if (l!=null) nNonzero++;
Question[] questions=new Question[nNonzero];
nNonzero=0;
for (int mask=0; mask<1<<nPeople; mask++) {
if (count[mask]==null) continue;
questions[nNonzero++]=new Question(mask, count[mask]);
}
long best=0; int bestMask=0;
for (int mask=0; mask<1<<nPeople; mask++) {
//if this is a 1 bit, expected is positive
long constantToAdd=0;
for (int i=0; i<nPeople; i++) if ((mask&(1<<i))!=0) constantToAdd+=expectedScores[i]; else constantToAdd-=expectedScores[i];
long bestOtherDist=bestOtherDist(mask, nQuestions, nPeople, questions, false);
if (bestOtherDist+constantToAdd>best) {
best=bestOtherDist+constantToAdd;
bestMask=mask;
}
// System.out.println("For mask "+mask+" "+constantToAdd+" "+bestOtherDist);
}
// out.println(best+" "+bestMask);
finalAns=new int[nQuestions];
bestOtherDist(bestMask, nQuestions, nPeople, questions, true);
for (int i=0; i<nQuestions; i++) {
out.print(finalAns[i]+" ");
}
out.println();
}
out.close();
}
static int[] finalAns;
static long bestOtherDist(int mask, int nQuestions, int nPeople,
Question[] questions, boolean markAns) {
for (Question q:questions) {
q.netValue=0;
for (int i=0; i<nPeople; i++) {
if ((q.mask&(1<<i))!=0) {
if ((mask&(1<<i))!=0) {
q.netValue--;
}
else {
q.netValue++;
}
}
}
}
Arrays.sort(questions);
long ans=0;
int next=1;
for (Question qq:questions) {
// for (int i=0; i<qq.count; i++) {
// ans+=next*qq.netValue;
// next++;
// }
for (int i:qq.originalPositions) {
ans+=next*qq.netValue;
if (markAns) finalAns[i]=next;
next++;
}
}
return ans;
}
static class Question implements Comparable<Question> {
int mask;
int netValue;
int count;
ArrayList<Integer> originalPositions;
public Question(int mask, ArrayList<Integer> originalPositions) {
this.mask=mask;
this.count=originalPositions.size();
this.originalPositions=originalPositions;
}
public int compareTo(Question o) {
return Integer.compare(netValue, o.netValue);
}
}
static final Random random=new Random();
static final int mod=1_000_000_007;
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
static long mul(long a, long b) {
return (a*b)%mod;
}
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);
}
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());
}
int[] readArray(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());
}
}
}
|
Let's call a set of positive integers a_1, a_2, ..., a_k quadratic if the product of the factorials of its elements is a square of an integer, i. e. ∏_{i=1}^{k} a_i! = m^2, for some integer m.
You are given a positive integer n.
Your task is to find a quadratic subset of a set 1, 2, ..., n of maximum size. If there are multiple answers, print any of them.
Input
A single line contains a single integer n (1 ≤ n ≤ 10^6).
Output
In the first line, print a single integer — the size of the maximum subset. In the second line, print the subset itself in an arbitrary order.
Examples
Input
1
Output
1
1
Input
4
Output
3
1 3 4
Input
7
Output
4
1 4 5 6
Input
9
Output
7
1 2 4 5 6 7 9 | #include <bits/stdc++.h>
using ULL = unsigned long long;
std::vector<int> spfS(int N) {
std::vector<int> sp(N);
std::iota(sp.begin(), sp.end(), 0);
for (int i = 2; i * i < N; ++i)
if (sp[i] == i) {
for (int j = i * i; j < N; j += i)
if (sp[j] == j) {
sp[j] = i;
}
}
return sp;
}
std::vector<int> spf(int N) {
std::vector<int> sp(N), p{0, 2};
p.reserve(N);
for (int i = 2; i < N; i += 2) sp[i] = 2;
for (int i = 1; i < N; i += 2) sp[i] = i;
for (int i = 3; i < N; i += 2) {
if (sp[i] == i) p.emplace_back(i);
for (int j = 2, np = (int)p.size(); j < np && p[j] <= sp[i] && i * p[j] < N;
++j) {
sp[i * p[j]] = p[j];
}
}
return sp;
}
std::mt19937_64 rnd64(
std::chrono::steady_clock::now().time_since_epoch().count());
void solve() {
int n;
std::cin >> n;
auto sp = spfS(n + 1);
std::vector<ULL> hsh(n + 1);
for (int i = 2; i <= n; ++i) {
if (sp[i] == i) {
hsh[i] = rnd64();
} else {
hsh[i] = hsh[i / sp[i]] ^ hsh[sp[i]];
}
}
ULL ans = 0;
for (int i = n; i > 1; i -= 2) ans ^= hsh[i];
if (ans == 0) {
std::cout << n << '\n';
for (int i = 1; i <= n; ++i) std::cout << i << " \n"[i == n];
return;
}
std::map<ULL, int> mp;
for (int i = 2; i <= n; ++i) hsh[i] ^= hsh[i - 1];
for (int i = 1; i <= n; ++i) mp[hsh[i]] = i;
if (auto it = mp.find(ans); it != mp.end()) {
std::cout << n - 1 << '\n';
for (int i = 1; i <= n; ++i) {
if (i != it->second) std::cout << i << ' ';
}
std::cout << '\n';
return;
}
for (int i = 2; i <= n; ++i) {
ULL need = ans ^ hsh[i];
auto it = mp.find(need);
if (it != mp.end()) {
std::cout << n - 2 << '\n';
for (int j = 1; j <= n; ++j) {
if (j != it->second && j != i) {
std::cout << j << ' ';
}
}
std::cout << '\n';
return;
}
}
assert(n % 4 == 3);
std::cout << n - 3 << '\n';
std::cout << 1;
for (int i = 3; i < n; ++i) {
if (i != n / 2) std::cout << ' ' << i;
}
std::cout << '\n';
}
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
int cas = 1;
while (cas--) {
solve();
}
return 0;
}
|
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).
In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.
Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell.
<image> Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes.
Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the time for the robot to do its job.
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.
A test case consists of only one line, containing six integers n, m, r_b, c_b, r_d, and c_d (1 ≤ n, m ≤ 100, 1 ≤ r_b, r_d ≤ n, 1 ≤ c_b, c_d ≤ m) — the sizes of the room, the initial position of the robot and the position of the dirt cell.
Output
For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.
Example
Input
5
10 10 6 1 2 8
10 10 9 9 1 1
9 8 5 6 2 1
6 9 2 2 5 8
2 2 1 1 2 1
Output
7
10
9
3
0
Note
In the first example, the floor has the size of 10× 10. The initial position of the robot is (6, 1) and the position of the dirty cell is (2, 8). See the illustration of this example in the problem statement.
In the second example, the floor is the same, but the initial position of the robot is now (9, 9), and the position of the dirty cell is (1, 1). In this example, the robot went straight to the dirty cell and clean it.
<image>
In the third example, the floor has the size 9 × 8. The initial position of the robot is (5, 6), and the position of the dirty cell is (2, 1).
<image>
In the fourth example, the floor has the size 6 × 9. The initial position of the robot is (2, 2) and the position of the dirty cell is (5, 8).
<image>
In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.
<image> | import java.io.*;
public class CP {
static void giveTime(int n, int m, int rb, int cb, int rd, int cd){
boolean colForward = true;
boolean rowForward = true;
int time = 0;
while((rb!=rd)&&(cb!=cd)){
if((rb==n)&&(rowForward)){
rowForward = false;
}
if((rb==1)&&(!rowForward)){
rowForward = true;
}
if((cb==m)&&(colForward)){
colForward = false;
}
if((cb==1)&&(!colForward)){
colForward = true;
}
if(rowForward) rb++;
else rb--;
if(colForward) cb++;
else cb--;
time++;
}
System.out.println(time);
}
public static void main(String[] args)throws Exception{
DataInputStream sc = new DataInputStream(System.in);
int T = Integer.parseInt(sc.readLine());
for(int i = 0; i < T; i++){
String[] str = sc.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int m = Integer.parseInt(str[1]);
int rb = Integer.parseInt(str[2]);
int cb = Integer.parseInt(str[3]);
int rd = Integer.parseInt(str[4]);
int cd = Integer.parseInt(str[5]);
giveTime(n, m, rb, cb, rd, cd);
}
}
} |
Alice and Bob play the following game. Alice has a set S of disjoint ranges of integers, initially containing only one range [1, n]. In one turn, Alice picks a range [l, r] from the set S and asks Bob to pick a number in the range. Bob chooses a number d (l ≤ d ≤ r). Then Alice removes [l, r] from S and puts into the set S the range [l, d - 1] (if l ≤ d - 1) and the range [d + 1, r] (if d + 1 ≤ r). The game ends when the set S is empty. We can show that the number of turns in each game is exactly n.
After playing the game, Alice remembers all the ranges [l, r] she picked from the set S, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers d from Alice's ranges, and so he asks you for help with your programming skill.
Given the list of ranges that Alice has picked ([l, r]), for each range, help Bob find the number d that Bob has picked.
We can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 1000).
Each of the next n lines contains two integers l and r (1 ≤ l ≤ r ≤ n), denoting the range [l, r] that Alice picked at some point.
Note that the ranges are given in no particular order.
It is guaranteed that the sum of n over all test cases does not exceed 1000, and the ranges for each test case are from a valid game.
Output
For each test case print n lines. Each line should contain three integers l, r, and d, denoting that for Alice's range [l, r] Bob picked the number d.
You can print the lines in any order. We can show that the answer is unique.
It is not required to print a new line after each test case. The new lines in the output of the example are for readability only.
Example
Input
4
1
1 1
3
1 3
2 3
2 2
6
1 1
3 5
4 4
3 6
4 5
1 6
5
1 5
1 2
4 5
2 2
4 4
Output
1 1 1
1 3 1
2 2 2
2 3 3
1 1 1
3 5 3
4 4 4
3 6 6
4 5 5
1 6 2
1 5 3
1 2 1
4 5 5
2 2 2
4 4 4
Note
In the first test case, there is only 1 range [1, 1]. There was only one range [1, 1] for Alice to pick, and there was only one number 1 for Bob to pick.
In the second test case, n = 3. Initially, the set contains only one range [1, 3].
* Alice picked the range [1, 3]. Bob picked the number 1. Then Alice put the range [2, 3] back to the set, which after this turn is the only range in the set.
* Alice picked the range [2, 3]. Bob picked the number 3. Then Alice put the range [2, 2] back to the set.
* Alice picked the range [2, 2]. Bob picked the number 2. The game ended.
In the fourth test case, the game was played with n = 5. Initially, the set contains only one range [1, 5]. The game's turn is described in the following table.
Game turn| Alice's picked range| Bob's picked number| The range set after
---|---|---|---
Before the game start| | | \{ [1, 5] \}
1| [1, 5]| 3| \{ [1, 2], [4, 5] \}
2| [1, 2]| 1| \{ [2, 2], [4, 5] \}
3| [4, 5]| 5| \{ [2, 2], [4, 4] \}
4| [2, 2]| 2| \{ [4, 4] \}
5| [4, 4]| 4| \{ \} (empty set) | # from operator import itemgetter
t = int(input())
for _ in range(t):
n = int(input())
a = []
for i in range(n):
x,y = map(int,input().split())
d = y-x
a.append([d,x,y])
a.sort(reverse = True)
for i in range(n):
mx = 0
for j in range(i+1,n):
if a[i][1] == a[j][1]:
if mx<a[j][2]:
mx = a[j][2]
mn = n + 1
for j in range(i+1,n):
if a[i][2] == a[j][2]:
if mn>a[j][1]:
mn = a[j][1]
if mx != 0 and mn != (n+1):
a[i].append((mn + mx)//2)
elif mx == 0:
a[i].append(a[i][1])
elif mn == n+1:
a[i].append(a[i][2])
# ans = sorted(a, key = itemgetter(3))
for i in range(n):
print(a[i][1],a[i][2],a[i][3])
print()
|
There are n heaps of stone. The i-th heap has h_i stones. You want to change the number of stones in the heap by performing the following process once:
* You go through the heaps from the 3-rd heap to the n-th heap, in this order.
* Let i be the number of the current heap.
* You can choose a number d (0 ≤ 3 ⋅ d ≤ h_i), move d stones from the i-th heap to the (i - 1)-th heap, and 2 ⋅ d stones from the i-th heap to the (i - 2)-th heap.
* So after that h_i is decreased by 3 ⋅ d, h_{i - 1} is increased by d, and h_{i - 2} is increased by 2 ⋅ d.
* You can choose different or same d for different operations. Some heaps may become empty, but they still count as heaps.
What is the maximum number of stones in the smallest heap after the process?
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 2⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (3 ≤ n ≤ 2 ⋅ 10^5).
The second lines of each test case contains n integers h_1, h_2, h_3, …, h_n (1 ≤ h_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum number of stones that the smallest heap can contain.
Example
Input
4
4
1 2 10 100
4
100 100 100 1
5
5 1 1 1 8
6
1 2 3 4 5 6
Output
7
1
1
3
Note
In the first test case, the initial heap sizes are [1, 2, 10, 100]. We can move the stones as follows.
* move 3 stones and 6 from the 3-rd heap to the 2-nd and 1 heap respectively. The heap sizes will be [7, 5, 1, 100];
* move 6 stones and 12 stones from the last heap to the 3-rd and 2-nd heap respectively. The heap sizes will be [7, 17, 7, 82].
In the second test case, the last heap is 1, and we can not increase its size.
In the third test case, it is better not to move any stones.
In the last test case, the final achievable configuration of the heaps can be [3, 5, 3, 4, 3, 3]. | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using PII = pair<long long, long long>;
using VI = vector<long long>;
string to_string(string s) { return '"' + s + '"'; }
string to_string(const char* s) { return to_string((string)s); }
string to_string(bool b) { return (b ? "true" : "false"); }
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
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;
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
const ll md = 1000000007;
long long n;
vector<long long> V;
bool check(long long mid) {
VI W = V;
for (int64_t i = (n - 1), _b = (2); i >= _b; --i) {
if (W[i] < mid) {
return false;
}
long long give = (W[i] - mid) / 3;
if (give * 3 > V[i]) {
give = V[i] / 3;
}
W[i] -= give * 3;
W[i - 1] += give;
W[i - 2] += give * 2;
}
for (long long _n = n, i = 0; i < _n; ++i) {
if (W[i] < mid) return false;
}
return true;
}
void solve() {
cin >> n;
V.resize(n);
long long mx = 0;
for (long long _n = n, i = 0; i < _n; ++i) {
cin >> V[i];
mx = max(mx, V[i]);
}
long long l = 1, r = mx;
while (l + 1 < r) {
long long mid = (l + r) / 2;
if (check(mid)) {
l = mid;
} else {
r = mid;
}
}
if (check(r)) {
cout << r << "\n";
} else {
cout << l << "\n";
}
}
int32_t main() {
ios_base::sync_with_stdio(false), cin.tie(0);
long long t;
cin >> t;
while (t--) solve();
}
|
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).
In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.
Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell.
After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \frac p {100} only, and not performed with probability 1 - \frac p {100}. The cleaning or not cleaning outcomes are independent each second.
Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the expected time for the robot to do its job.
It can be shown that the answer can be expressed as an irreducible fraction \frac x y, where x and y are integers and y not ≡ 0 \pmod{10^9 + 7} . Output the integer equal to x ⋅ y^{-1} mod (10^9 + 7). In other words, output such an integer a that 0 ≤ a < 10^9 + 7 and a ⋅ y ≡ x \pmod {10^9 + 7}.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10). Description of the test cases follows.
A test case consists of only one line, containing n, m, r_b, c_b, r_d, c_d, and p (4 ≤ n ⋅ m ≤ 10^5, n, m ≥ 2, 1 ≤ r_b, r_d ≤ n, 1 ≤ c_b, c_d ≤ m, 1 ≤ p ≤ 99) — the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.
Output
For each test case, print a single integer — the expected time for the robot to clean the dirty cell, modulo 10^9 + 7.
Example
Input
6
2 2 1 1 2 1 25
3 3 1 2 2 2 25
10 10 1 1 10 10 75
10 10 10 10 1 1 75
5 5 1 3 2 2 10
97 98 3 5 41 43 50
Output
3
3
15
15
332103349
99224487
Note
In the first test case, the robot has the opportunity to clean the dirty cell every second. Using the [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution), we can find out that with the success rate of 25\%, the expected number of tries to clear the dirty cell is \frac 1 {0.25} = 4. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is 3.
<image> Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes.
In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example.
<image> Illustration for the second example.
The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result. | #include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 5, M = 2e3 + 5, mod = 1e9 + 7;
inline long long read() {
long long 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 << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
void write(long long x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
void wt(long long x) {
write(x);
puts("");
}
long long qmi(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) (res *= a) %= mod;
(a *= a) %= mod;
b >>= 1;
}
return res;
}
void solve() {
long long n = read(), m = read(), rb = read(), cb = read(), rd = read(),
cd = read(), p = read();
vector<long long> v;
long long x = rb, y = cb, sec = 0, dx = 1, dy = 1,
proc = (100 - p) * qmi(100, mod - 2) % mod, sum = 0, cnt = 0;
p = 1;
while (1) {
if (x == rd || y == cd) {
(p *= proc) %= mod;
(sum += p) %= mod;
} else
(sum += p) %= mod;
if (x + dx > n || x + dx < 1) dx = -dx;
if (y + dy > m || y + dy < 1) dy = -dy;
x += dx, y += dy;
if (x == rb && y == cb) cnt++;
if (cnt == 4) break;
}
long long tt = qmi(((1 - p) % mod + mod) % mod, mod - 2);
wt(((sum * tt % mod) + mod) % mod);
}
signed main() {
long long _ = 1;
cin >> _;
while (_--) solve();
return 0;
}
|
A binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not have the left child, and r_u = 0 if the node u does not have the right child.
Each node has a string label, initially is a single character c_u. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let f(u) be the string representation of the tree rooted at the node u. f(u) is defined as follows: $$$ f(u) = \begin{cases} <empty string>, & if u = 0; \\\ f(l_u) + c_u + f(r_u) & otherwise, \end{cases} where +$$$ denotes the string concatenation operation.
This way, the string representation of the tree is f(1).
For each node, we can duplicate its label at most once, that is, assign c_u with c_u + c_u, but only if u is the root of the tree, or if its parent also has its label duplicated.
You are given the tree and an integer k. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most k nodes?
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
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5).
The second line contains a string c of n lower-case English letters, where c_i is the initial label of the node i for 1 ≤ i ≤ n. Note that the given string c is not the initial string representation of the tree.
The i-th of the next n lines contains two integers l_i and r_i (0 ≤ l_i, r_i ≤ n). If the node i does not have the left child, l_i = 0, and if the node i does not have the right child, r_i = 0.
It is guaranteed that the given input forms a binary tree, rooted at 1.
Output
Print a single line, containing the lexicographically smallest string representation of the tree if at most k nodes have their labels duplicated.
Examples
Input
4 3
abab
2 3
0 0
0 4
0 0
Output
baaaab
Input
8 2
kadracyn
2 5
3 4
0 0
0 0
6 8
0 7
0 0
0 0
Output
daarkkcyan
Input
8 3
kdaracyn
2 5
0 3
0 4
0 0
6 8
0 7
0 0
0 0
Output
darkcyan
Note
The images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node.
Here is the tree for the first example. Here we duplicated the labels of nodes 1 and 3. We should not duplicate the label of node 2 because it would give us the string "bbaaab", which is lexicographically greater than "baaaab".
<image>
In the second example, we can duplicate the labels of nodes 1 and 2. Note that only duplicating the label of the root will produce a worse result than the initial string.
<image>
In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node 3, by duplicating it we must also duplicate the label of the node 2, which produces a worse result.
<image>
There is no way to produce string "darkkcyan" from a tree with the initial string representation "darkcyan" :(. | #include <bits/stdc++.h>
const int N = 200005;
int n, k, rem;
char c[N];
int ls[N], rs[N], fa[N];
int cst[N];
int from[N];
bool vis[N], coled[N];
void dfs(int x, int &tt) {
if (!x) return;
dfs(ls[x], tt), from[++tt] = x, dfs(rs[x], tt);
return;
}
inline void add(int x) {
for (int i = 1; x; x = ls[x], ++i) cst[x] = i;
return;
}
inline void col(int x) {
while (x && !coled[x]) {
--rem;
add(rs[x]);
coled[x] = 1;
x = fa[x];
}
return;
}
int main(void) {
scanf("%d%d%s", &n, &k, c + 1), rem = k;
for (int i = 1; i <= n; ++i) {
scanf("%d%d", ls + i, rs + i);
if (ls[i]) fa[ls[i]] = i;
if (rs[i]) fa[rs[i]] = i;
}
int tt = 0;
dfs(1, tt);
vis[n] = 0;
for (int i = n - 1; i >= 1; --i)
if (c[from[i]] < c[from[i + 1]] ||
(c[from[i]] == c[from[i + 1]] && vis[i + 1]))
vis[i] = 1;
add(1);
for (int i = 1; i <= n; ++i) {
if (coled[from[i]]) continue;
if (cst[from[i]] != 0 && cst[from[i]] <= rem && vis[i]) col(from[i]);
}
for (int i = 1; i <= n; ++i) {
putchar(c[from[i]]);
if (coled[from[i]]) putchar(c[from[i]]);
}
putchar('\n');
return 0;
}
|
Three little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the n-th minute, the convention ends.
The big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and eat exactly x pigs. Then he will get away.
The wolf wants Gregor to help him figure out the number of possible attack plans that involve eating exactly x pigs for various values of x (1 ≤ x ≤ 3n). Two attack plans are considered different, if they occur at different times or if the sets of little pigs to eat are different.
Note that all queries are independent, that is, the wolf does not eat the little pigs, he only makes plans!
Input
The first line of input contains two integers n and q (1 ≤ n ≤ 10^6, 1 ≤ q ≤ 2⋅ 10^5), the number of minutes the convention lasts and the number of queries the wolf asks.
Each of the next q lines contains a single integer x_i (1 ≤ x_i ≤ 3n), the number of pigs the wolf will eat in the i-th query.
Output
You should print q lines, with line i representing the number of attack plans if the wolf wants to eat x_i pigs. Since each query answer can be large, output each answer modulo 10^9+7.
Examples
Input
2 3
1
5
6
Output
9
6
1
Input
5 4
2
4
6
8
Output
225
2001
6014
6939
Note
In the example test, n=2. Thus, there are 3 pigs at minute 1, and 6 pigs at minute 2. There are three queries: x=1, x=5, and x=6.
If the wolf wants to eat 1 pig, he can do so in 3+6=9 possible attack plans, depending on whether he arrives at minute 1 or 2.
If the wolf wants to eat 5 pigs, the wolf cannot arrive at minute 1, since there aren't enough pigs at that time. Therefore, the wolf has to arrive at minute 2, and there are 6 possible attack plans.
If the wolf wants to eat 6 pigs, his only plan is to arrive at the end of the convention and devour everybody.
Remember to output your answers modulo 10^9+7! | #include <bits/stdc++.h>
using namespace std;
vector<long long> inverses(int n, int P) {
vector<long long> inv(n + 1, 1);
for (int i = 2; i <= n; ++i) inv[i] = inv[P % i] * (P - P / i) % P;
return inv;
}
const int mod = 1e9 + 7;
namespace combi {
const int N = 3e6 + 10;
int fac[N], ifac[N];
void init() {
fac[0] = ifac[0] = 1;
auto inv = inverses(N, mod);
for (int i = 1; i < N; ++i) {
fac[i] = (long long)fac[i - 1] * i % mod;
ifac[i] = (long long)ifac[i - 1] * inv[i] % mod;
}
}
int comb(int n, int k) {
return (long long)fac[n] * ifac[n - k] % mod * ifac[k] % mod;
}
} // namespace combi
using namespace combi;
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
init();
int n, Q;
cin >> n >> Q;
int sz = 3 * (n + 1);
vector<int> p(sz + 1);
for (int i = 1; i <= sz; ++i) p[i] = comb(sz, i);
for (int i = sz; i >= 3; --i) {
p[i - 1] = ((p[i - 1] - 3LL * p[i]) % mod + mod) % mod;
p[i - 2] = ((p[i - 2] - 3LL * p[i]) % mod + mod) % mod;
}
p.erase(p.begin(), p.begin() + 3);
for (int x; Q--;) {
cin >> x;
cout << p[x] << "\n";
}
return 0;
}
|